【发布时间】:2013-01-11 12:27:12
【问题描述】:
我有代码:
class A {
override def toString = "object class A"
}
class B extends A {
override def toString = "object class B"
}
class Cell[+T](init: T) {
private[this] var current: T = init
def get: T = current
def set(x: T) { current = x }
}
val cB = new Cell[B](new B)
println(cB.get)
val cA: Cell[A] = cB
println(cA.get)
但我有错误:def set(x: T) { current = x }
错误:协变类型 T 出现在类型 T 的逆变位置 值 x def set(x: T) { current = x }
请解释
【问题讨论】:
-
除了有见地的答案之外,为什么还需要显式的私有引用和 getter/setter? Scala 为您做到这一点:
class Cell[+T](val t: T) {...}
标签: scala