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?
collections access-modifiers types scala covariance
Matt Kantor Mar 24 '15 at 17:13 2015-03-24 17:13
source share