문제

Im reading this page http://www.scala-lang.org/node/137, I understand what covariance is and lower bounds as well, but what it's not clear is this line:

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

why elem has to be an instance of a supertype of T, if ListNode is already covariant why elem cannot be prepended to the current list.

도움이 되었습니까?

해결책

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 were allowed:

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

Since Foo is covariant on T, this is valid (a simple upcast, since a Foo[Sub] is a Foo[Super]):

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

Now foo is, as far as we know, a Foo[Super] like any other, but its bar method won't work, because the bar implementation requires a Sub:

foo.bar(sup) // would cause error!
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top