The definition of a generic method scala

Generics
scala Like Java, class and character, generic methods can support. When we study the set, usually it comes to generics.
scala> val list1:List[String] = List("1", "2", "3") list1: List[String] = List(1, 2, 3)
Then how to define your own generic it?
Defines a generic method
in the scala using brackets to define the type of parameters.
Syntax:
def 方法名[泛型名称](..) = { //... }
Example
illustration
by a method for obtaining an intermediate element array of any type
is not directly consider the generic implementation (based Array [Int] implementation)
was added to support the generic
reference code
is not considered generic implementation

  def getMiddle(arr:Array[Int]) = arr(arr.length / 2)

  def main(args: Array[String]): Unit = {
    val arr1 = Array(1,2,3,4,5)

    println(getMiddle(arr1))
  }

Added generic support

def getMiddleElement[T](array:Array[T]) =
array(array.length / 2)

def main(args: Array[String]): Unit = {
    println(getMiddleElement(Array(1, 2, 3, 4, 5)))
    println(getMiddleElement(Array("a", "b", "c", "d", "e")))
}

Here Insert Picture Description
result:
Here Insert Picture Description

Published 151 original articles · won praise 339 · Views 230,000 +

Guess you like

Origin blog.csdn.net/qq_45765882/article/details/104335833