我想在Scala中做一些我不太確定的事情。我喜歡來自社區的一些反饋。協調多個通用構造函數的參數
說我有一些「東西」密封的特點,它的一些具體的擴展,並與該性狀一些執行工作的泛型類..
sealed trait Thing
class CoolThing extends Thing
class OtherThing extends Thing
class BoxOfThings[T <: Thing]
現在,我可以定義另一個類處理,像這樣兩個人的事情盒子'..
class PairOfBoxes(boxOne: BoxOfThings[_ <: Thing], boxTwo: BoxOfThings[_ <: Thing])
然而,這裏是完美的罰款創造PairOfBoxes
與CoolThing
■一個盒子和其他的OtherThing
秒。我想聲明boxOne
和boxTwo
包含相同類型的Thing
..是不是可能?
例如:
// Cool things..
val boxOfCoolThings = new BoxOfThings[CoolThing]
val anotherBoxOfCoolThings = new BoxOfThings[CoolThing]
// Other things..
val boxOfOtherThings = new BoxOfThings[OtherThing]
// A pair of cool boxes, no problem:
new PairOfBoxes(boxOfCoolThings, anotherBoxOfCoolThings)
// A pair of different boxes, compiles but I don't want it to:
new PairOfBoxes(boxOfOtherThings, anotherBoxOfCoolThings)
我可以通過使PairOfBoxes
通用本身,像這樣做..
class TypedPairOfBoxes[T <: BoxOfThings[_ <: Thing]](boxOne: T, boxTwo: T)
它的工作原理,但它的醜陋..
// A pair of cool boxes, no problem:
new TypedPairOfBoxes[BoxOfThings[CoolThing]](boxOfCoolThings, anotherBoxOfCoolThings)
// A pair of different boxes, doesn't compile:
val mixedPair = new TypedPairOfBoxes[BoxOfThings[CoolThing]](boxOfOtherThings, anotherBoxOfCoolThings)
我想避免這是我可以。它將問題推向上游並迫使我們指定每個TypedPairOfBoxes
的內容。簡單地使用一個無類型的PairOfBoxes
將是理想的,它斷言它的參數是相同的類型。
可能嗎?
謝謝!
非常好,請你提供一個解釋爲什麼這個工作原理? – 2013-02-13 11:03:43