我對Scala中的類型投影有限制。假設我有以下代碼:斯卡拉類型投影的正確限制是什麼?
sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color
trait Item {
type Colors <: Color
}
object RedGreenItem extends Item {
type Colors = Red.type with Green.type
}
object Test {
def foo[I <: Item, C >: I#Colors <: Color](item : I, color : C) : Unit = {
// ...
}
def main(args : Array[String]) : Unit = {
foo(RedGreenItem, Blue) // <- why does it compile?
}
}
什麼其實我是想實現的是能夠傳遞給foo
作爲第二個參數只在Item#Colors
定義的顏色(因此限制C >: I#Colors
)。 但事實證明,我可以通過其他所有顏色(在這種情況下爲Blue
)。
,我可以看到這個問題的根源,如果我寫的foo
方法是這樣的:
def foo[I <: Item, C >: I#Colors <: Color : TypeTag](item : I, color : C) : Unit = {
// ...
println(s"type = ${typeOf[C]}")
}
// type = Color
所以,與其Blue.type
類型被推斷爲Color
,因此任何顏色是好的。 如果我刪除限制>: I#Colors
,那麼該類型是正確的決定:
def foo[I <: Item, C <: Color : TypeTag](item : I, color : C) : Unit = {
// ...
println(s"type = ${typeOf[C]}")
}
// type = Blue.type
所以,我的問題是:我如何能實現我的目標是有限制的顏色有一個允許的類型,而不是編譯除此以外?非常感謝,並提前抱歉,也許是一個愚蠢的問題。
謝謝賈斯珀!這看起來像我在找什麼。我對HList有一些想法,所以我打算這樣做。 – Max