0
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

pedrofurla
  • 12,763
  • 1
  • 38
  • 49
PheniX Tylor
  • 41
  • 1
  • 4
  • 2
    Because if prefix the argument with a `val` then it becomes a public field and as such a getter is created using **T** as its return type, which is not possible because **T** is _contravariant_. – Luis Miguel Mejía Suárez Oct 05 '20 at 19:38

1 Answers1

2

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.

user
  • 7,435
  • 3
  • 14
  • 44