我已代碼:誤差定義協變和逆變類型
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 }
error: covariant type T occurs in contravariant position in type T of value x def set(x: T) { current = x }
解釋,請
除了有見地的答案,爲什麼你需要明確私有引用和getter/setter方法? Scala爲你做這件事:'class Cell [+ T](val t:T){...}' –