Abstract Types(抽象类型) && Parameterized Types(参数化类型)
Scala的抽象类型成员(Abstract Type Members)没有和Java等同的。 两个语言中,类,接口(Java),特质(Scala)都可以有方法和字段作为成员。
Scala的类(class)或特质(trait)可以有类型成员 ,下面例子是抽象类型成员:
object app_main_8 extends App { // 通过给出这两个成员的具体定义来对这个类型进行实例化 val abs = new AbsCell { override type T = Int override val init: T = 12 override var me: S = "liyanxin" } println(abs.getMe) println(abs.getInit) } trait Cell { // 抽象类型成员S type S var me: S def getMe: S = me def setMe(x: S): Unit = { me = x } } /** * AbsCell 类既没有类型参数也没有值参数, * 而是定义了一个抽象类型成员 T 和一个抽象值成员 init。 */ abstract class AbsCell extends Cell { //在子类内部具体化抽象类型成员S override type S = String // 抽象类型成员 T type T val init: T private var value: T = init def getInit: T = value def setInit(x: T): Unit = { value = x } }
运行并输出:
liyanxin 0
参考:http://alanwu.iteye.com/blog/483959
https://github.com/wecite/papers/blob/master/An-Overview-of-the-Scala-Programming-Language/5.Abstraction.md
关于下面两者的区别:
abstract class Buffer { type T val element: T }
rather that generics, for example,
abstract class Buffer[T] { val element: T }
请见:http://stackoverflow.com/questions/1154571/scala-abstract-types-vs-generics
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
==============END==============