I have code:
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)
but I have error in line: 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 }
Explain, please
Contravariant positions for a type are (among others) any positions that allow you to pass an instance of that type to a method. So all method parameter types are in contravariant positions. Since you declared T as covariant (
+T), the compiler won’t allow this. Your only options are:TinvariantCellandCellthus becomes immutable.CellimmutableIf the compiler allowed you to have a set method as you implemented it, that would make the type system unsafe, since it would allow you to write: