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) }
时间: 2024-11-25 13:14:21