[英]why val work but var doesn't in constructor in this case (scala)
[英]why the constructor doesn't work with covariance in scala
我有以下类定义,C定义为采用协方差类型参数+ T,并且尝试将另一个构造函数方法定义为快捷方式,但我无法使其与T类型一起使用。
class C[+T](val value: T, children: List[C[T]]) {
def this(value: T) = this(value, Nil) //it fail with covariant type not allowed here
def this[U >: T](value: U) = this(value, Nil)//it fail with can't find symbol U
def replace[U >: T](t: U) = new C(t, children) //it success
}
我认为第二个应该像replace方法一样工作,但事实并非如此。 有人可以解释一下这背后的原因吗,为什么替换有效,却不可行? 正确的方法 谢谢。
为什么替换有效,但不是这样?
构造函数不能使用类型参数(这是我在2.10中收到的消息,而can't find symbol U
)。 但是即使可以, replace
也会返回C[U]
,而构造函数也必须返回C[T]
。
正确的方法
使它成为伴随对象中的方法:
object C {
def apply[U](value: U) = new C(value, Nil) // note that you no longer need T here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.