sealed trait X { val x: String }
case class A(x: String) extends X
case class B(x: String) extends X
我在X
特質定義的copy
方法:
def copy(x: X, newValue: String): X = x match {
case A(_) => A(newValue)
case B(_) => B(newValue)
}
但是,我認爲我可以做的更好,即精確。
因爲在技術上,僅僅因爲輸入了A
,所以可以輸出B
,因爲B
是X
的子類。
所以,我想:
def copyBetter[T <: X](x: T, newValue: String): T = x match {
case A(_) => A(newValue)
case B(_) => B(newValue)
}
但是,我得到了編譯時錯誤:
<console>:17: error: type mismatch;
found : A
required: T
case A(_) => A(newValue)
^
<console>:18: error: type mismatch;
found : B
required: T
case B(_) => B(newValue)
^
我如何能實現copyBetter
與給定的簽名?
我想我有一個類似的問題,我解決了它返回'X',這裏的問題是你的返回類型是動態的,你不能找出哪個類型'T'會在調用之前,這有點不同從普通方法調用到泛型方法,在這種情況下,您可以事先指定類型,因爲您知道將要返回的內容,在這裏您不能。 –
我會看看沒有形狀,只是爲了檢查你的問題是否可以與之相對應。 – Reactormonk