Reputation: 41
class Contravariant[-T](val other:T)
error: contravariant type T occurs in covariant position in type T of value other
However this one succeeds
class MMX[-T](x:T)
What is the difference?
Thanks
Upvotes: 0
Views: 54
Reputation: 7604
As Luis Miguel Mejía Suárez said, in the first example, other
is a field, and fields cannot be contravariant (as Dmytro Mitin pointed out, not fields with modifier private[this]
or protected[this]
), although they can be covariant. Consider this example, assuming your first example worked:
class Contravariant[-T](val other: T)
val stringList = List[Contravariant[String]](new Contravariant[Any](1))
val string: String = stringList.head.other //This can't work, because 1 is not a String
Here you can see what happens (I used @uncheckedVariance
to make it work).
In the second example, x
is simply a parameter to your constructor, and parameters can be contravariant, so it works.
Upvotes: 2