Scala constraints and covariance of the lower type

Im reading this page http://www.scala-lang.org/node/137 , I understand what covariance and lower bounds are, but that this is not clear:

Unfortunately, this program does not compile, since covariance annotation is possible only if the type variable is used only in covariant positions. Since a variable of type T appears as the parameter type of the prepend method, this rule is violated.

why elemshould it be an instance of a supertype T, if it is ListNodealready covariant, why elemcannot it be added to the current list.

+5
source share
1 answer
class Super             {override def toString = "Super"}
class Sub extends Super {override def toString = "Sub"; def subMethod {} }
val sup = new Super
val sub = new Sub

Imagine the following:

// invalid code
class Foo[+T] {
  def bar(x: T) = println(x)
}

Foo T, ( upcast, a Foo[Sub] Foo[Super]):

val foo : Foo[Super] = new Foo[Sub] {
  override def bar(x: Sub) = x.subMethod
}

Foo, , Foo[Super], , bar , bar Sub:

foo.bar(sup) // would cause error!
+2

All Articles