简体   繁体   English

为什么构造函数无法在Scala中使用协方差工作

[英]why the constructor doesn't work with covariance in scala

I have following class definition, C defined to take covariance type parameter +T, and I tried to define another constructor method as a shortcut, but I couldn't make it to work with type T. 我有以下类定义,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
}

I thought the the second this should work just like the replace method, but it doesn't. 我认为第二个应该像replace方法一样工作,但事实并非如此。 could some one explain what behind this, why replace works but not this? 有人可以解释一下这背后的原因吗,为什么替换有效,却不可行? and the right way to do this. 正确的方法 thanks. 谢谢。

why replace works but not this? 为什么替换有效,但不是这样?

Constructors can't take type parameters (and that's the message I get in 2.10 instead of can't find symbol U ). 构造函数不能使用类型参数(这是我在2.10中收到的消息,而can't find symbol U )。 But even if they could, replace returns C[U] and the constructor must return C[T] . 但是即使可以, replace也会返回C[U] ,而构造函数也必须返回C[T]

and the right way to do this 正确的方法

Make it a method in companion object: 使它成为伴随对象中的方法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM