简体   繁体   中英

Difference between 2 class definitions regarding contravariant type?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM