2

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?

Matt Kantor
  • 1,704
  • 1
  • 19
  • 37
  • See http://stackoverflow.com/q/28947134/3625 for the origin story of this question. – Matt Kantor Mar 24 '15 at 17:24
  • If you need more information about `private` vs `private[this]`, see: http://stackoverflow.com/questions/9698677/privatethis-vs-private – kiritsuku Mar 24 '15 at 17:41
  • 1
    http://stackoverflow.com/a/9727849/3625 *almost* answers my question, but @denisphillips mentions mutable vars as the important factor, while my example doesn't have any mutability. – Matt Kantor Apr 07 '15 at 22:25

0 Answers0