How can I use a pseudo-variant parameter of covariance type

The following code does not compile (in Scala 2.11):

case class CovariantClass[+R](value: R) {
  type T = R
  def get: R = value
}

object Main {
  def main(args: Array[String]): Unit ={
    println(CovariantClass[String]("hello").get)
  }
}

Error message:

Error:(4, 8) covariant type R occurs in invariant position in type R of type T
  type T = R
       ^

Why can't I use a covariant type parameter? If I delete the line type T = R, the code compiles and prints hello, so the alias seems to be a problem. Unfortunately, this means that I cannot create an alias for more complex types, for example, it type T = List[R]also does not compile, although it Listis covariant.

+4
source share
2 answers

From scala spec :

The right side of the type alias is always in an invariant position.

, T R . List[R], .

:

case class CovariantClass[+R](value: R) {
  type T[+R] = List[R]
  def get: R = value
}

, R, , , - .

+4

, , . :

case class CovariantClass[+R](value: R) {
  type T <: R
  def get: R = value
}

, , :

case class CovariantClass[+R](value: R) {
  type T = Int
  def get: R = value
  def put(x: T) {}
  def put2(x: R) {}
}

- , T, . , , , , . , put , put2 .

+3

All Articles