1
(斯卡拉2.11.8)更親切類型推斷
考慮下面的代碼片段:
class Case2 {
trait Container[+A] {
def addAll[B >: A, T2 <: Container[B]](that: T2): Boolean
}
def t1: Container[String] = ???
def t2: Container[Int] = ???
// Works
t1.addAll[Any, Container[Any]](t2)
// Errors:
//* type mismatch; found : Case2.this.Container[Int] required: T2
//* inferred type arguments [String,Case2.this.Container[Int]] do not conform to method addAll's type parameter bounds [B >: String,T2 <: Case2.this.Container[B]]
t1.addAll(t2)
}
爲什麼不能持續addAll
呼叫推斷正確的最小公用超類型?
不是一個答案,但你真的需要'T2'嗎? 'def addAll [B>:A](that:Container [B]):Boolean'應該可以工作,更像你通常在這種情況下看到的。 –
不幸的是,在實際的代碼中,依賴於'T2'的類型約束,所以我不認爲這是可能的。上面的代碼片段是我在調查原始代碼中的問題時提出的簡化代碼。 –
實際上,你似乎斷言'Container [Int] <:Container [B]'其中'B>:String'。如果您明確地將B設置爲任意,它將起作用(如您所見),但我認爲類型推斷系統不允許將「任何」替換爲「解決方案」。雖然我不是100%確定的。 – Phasmid