Question

Scala code:

class Cat[T] {
    def meow[K <: T] = ""
}

class Cat[-T] {
    def meow[K <: T] = ""
}

They can be compiled.

But when T is covariance, the following code can't be compiled:

class Cat[+T] {
    def meow[K <: T] = ""
}

The compiler prints:

error: covariant type T occurs in contravariant position in type  <: T of type K
       def meow[K <: T] = ""
                ^

The type on the right of <: must not be covariant? And why?

Was it helpful?

Solution

That would be unsound

with Jazz <: Music, Classical <: Music, but no relation between Jazz and Classical,

meow[K <: T] means that a Cat[Music] can meow in Jazz, Classical, or any choice of genre.

On the other hand, a Cat[Classical] meow cannot be Jazz.

But if you have covariant Cat[+T], then a Cat[Classical] <: Cat[Music] , so a Cat[Classical], being an eclectic Cat[Music] too, should be able to meow Jazz.

Contradiction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top