Abstract Types && Parameterized Typesgit
Scala的抽象类型成员(Abstract Type Members)没有和Java等同的。 github
两个语言中,类,接口(Java),特质(Scala)均可以有方法和字段做为成员。app
Scala的类(class)或特质(trait)能够有类型成员,下面例子是抽象类型成员:ide
object app_main 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/483959spa
关于下面二者的区别:code
abstract class Buffer { type T val element: T }
rather that generics, for example,orm
abstract class Buffer[T] { val element: T }
请见:http://stackoverflow.com/questions/1154571/scala-abstract-types-vs-genericsblog
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 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) }
==============END==============