簡體   English   中英

為什么構造函數無法在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM