Kul*_*mpa 5 scala covariance type-alias
以下代码无法编译(在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)
}
}
Run Code Online (Sandbox Code Playgroud)
错误消息是:
Error:(4, 8) covariant type R occurs in invariant position in type R of type T
type T = R
^
Run Code Online (Sandbox Code Playgroud)
为什么我不能为协变类型参数添加别名?如果我删除该行type T = R,代码编译并打印hello,所以别名似乎是问题.不幸的是,这意味着我无法为更复杂的类型创建别名,例如type T = List[R],虽然List是协变的,但也不会编译.
来自scala规范:
类型别名的右侧始终处于不变位置.
这意味着您无法创建别名T并R在右侧指定变体类型.这同样适用于List[R],因为它也是协变的.
但是,您可以使用类型参数提供类型别名:
case class CovariantClass[+R](value: R) {
type T[+R] = List[R]
def get: R = value
}
Run Code Online (Sandbox Code Playgroud)
如果您发现自己想要为type参数设置别名R,那么您应该首先将其命名为其他名称.
| 归档时间: |
|
| 查看次数: |
528 次 |
| 最近记录: |