Why does scalac only emit dispersion errors with specific access modifiers?

This code does not compile:

trait Invariant[T] trait Covariant[+T] { protected val example: Invariant[T] } 
 error: covariant type T occurs in invariant position in type => Invariant[T] of value example protected val example: Invariant[T] ^ one error found 

However, this code compiles just fine:

 trait Invariant[T] trait Covariant[+T] { protected[this] val example: Invariant[T] } 

After some experimentation, it seems that the variance error only occurs when the access modifier is not tied to this . Both of them do not work:

 val example: Invariant[T] private val example: Invariant[T] = ??? 

While private[this] working.

I see similar behavior when a type is contravariant rather than invariant.

I feel like I'm missing something about how a system like Scala works. Why does the compiler behave this way?

+2
collections access-modifiers types scala covariance
Mar 24 '15 at 17:13
source share

No one has answered this question yet.

See similar questions:

138
Why is the example not compiling, but how does (co-, contra- and in) variance work?
82
private [this] versus private
2
How to implement newBuilder for a custom Scala collection (with proper dispersion)?

or similar:

268
Does Swift have access modifiers?
127
Why covariance and contravariance do not support the type of value
12
Variation Annotations in Type Aliases
9
howto initializes a covariant variable?
3
Covariant type in contravariant position (specific case)
3
Can I make a trait covariant?
2
How to check covariant and contravariant position of an element in a function?
one
Return immutable. Covariant Type Card
one
How to define flatMap for a class with parameters of covariant / contravariant type?
0
The covariant type FParam occurs in a contravariant position in the type Seq [FParam] value guesses



All Articles