【发布时间】:2014-10-18 00:18:12
【问题描述】:
以下代码无法编译(在 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:(4, 8) covariant type R occurs in invariant position in type R of type T
type T = R
^
为什么我不能为协变类型参数设置别名?如果我删除行type T = R,代码编译并打印hello,所以别名似乎是问题所在。不幸的是,这意味着我无法为更复杂的类型创建别名,例如,type T = List[R] 也无法编译,尽管List 是协变的。
【问题讨论】:
标签: scala covariance type-alias