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 appears that the variance error occurs only when the access modifier is not scoped to this
. These both fail:
val example: Invariant[T]
private val example: Invariant[T] = ???
While private[this]
also works.
I see similar behavior when the type is contravariant instead of invariant.
I feel like I'm missing something about how Scala's type system works. Why does the compiler behave this way?