標籤:
Scala Parameterized Types_參數化型別_泛型
Scala supports parameterized types, which are very similar to generics in Java. (We could use the two terms interchangeably(可交換的),
but it’s more common to use “parameterized types” in the Scala community and “generics” in the Java community.) The most obvious difference is in the
syntax, where ????????Scala uses square brackets ([...] ), while Java uses angle brackets (<...>).????????
用型別參數化類
For example, a list of strings would be declared as follows:
class GenCell[T](init: T) { private var value: T = init def get: T = value //Unit相當於返回void def set(x: T): Unit = { value = x }}
在上面的定義中,“T”是一個型別參數,可被用在GenCell類和它的子類中。類參數可以是任意(arbitrary)的名字。用[]來包圍,而不是用()來包圍,用以和值參數進行區別。
用型別參數化函數
如下程式碼範例
class GenCell[T](init: T) { private var value: T = init def get: T = value //Unit相當於返回void def set(x: T): Unit = { value = x }}object app_main_7 extends App { //用T參數化函數 def swap[T](x: GenCell[T], y: GenCell[T]): Unit = { val t = x.get; x.set(y.get); y.set(t) } val x: GenCell[Int] = new GenCell[Int](1) val y: GenCell[Int] = new GenCell[Int](2) swap[Int](x, y) println(x.get) println(y.get)}
參考:https://github.com/wecite/papers/blob/master/An-Overview-of-the-Scala-Programming-Language/5.Abstraction.md
Scala Parameterized Types_參數化型別_泛型