Scala 协调多个泛型构造函数参数

Scala 协调多个泛型构造函数参数,scala,generics,types,Scala,Generics,Types,我正在尝试在Scala中做一些我不确定是否可行的事情。我希望社区能给我一些反馈 假设我有一个用于某个“东西”的密封特性,它的一些具体扩展,以及一个与该特性的一些实现一起工作的泛型类 sealed trait Thing class CoolThing extends Thing class OtherThing extends Thing class BoxOfThings[T <: Thing] 我可以通过使PairofBox本身具有通用性来实现这一点,就像这样 class Pair

我正在尝试在Scala中做一些我不确定是否可行的事情。我希望社区能给我一些反馈

假设我有一个用于某个“东西”的密封特性,它的一些具体扩展,以及一个与该特性的一些实现一起工作的泛型类

sealed trait Thing
class CoolThing extends Thing
class OtherThing extends Thing

class BoxOfThings[T <: Thing]
我可以通过使
PairofBox
本身具有通用性来实现这一点,就像这样

class PairOfBoxes(boxOne: BoxOfThings[_ <: Thing], boxTwo: BoxOfThings[_ <: Thing])
class TypedPairOfBoxes[T <: BoxOfThings[_ <: Thing]](boxOne: T, boxTwo: T)
我想避免这是我能做到的。它将问题推到上游,并迫使我们指定每个
typedpairofbox
的内容。最好只使用一个非类型化的
pairofbox
,它断言它的参数是相同类型的

可能吗


谢谢

我你只需要写为:

class TypedPairOfBoxes[T <: Thing](one: BoxOfThings[T], two: BoxOfThings[T])
class TypedPairOfBoxes[T新的TypedPairOfBoxes(另一个盒子,另一个盒子)
:15:错误:类型不匹配;
发现:一箱箱东西[其他东西]
必需:一箱箱物品[东西]

注意:另外一件事我会让它打开一段时间。这可以做得更干净吗?太好了,你能解释一下为什么这样做吗?
// 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)
// Both boxes contain cool things, no problem:
new TypedPairOfBoxes(boxOfCoolThings, anotherBoxOfCoolThing)

// These boxes contain different things, doesn't compile:
new TypedPairOfBoxes(boxOfOtherThings, anotherBoxOfCoolThing)
class TypedPairOfBoxes[T <: Thing](boxOne: BoxOfThings[T], boxTwo: BoxOfThings[T])
class TypedPairOfBoxes[T <: Thing](one: BoxOfThings[T], two: BoxOfThings[T])
scala> new TypedPairOfBoxes(boxOfOtherThings, anotherBoxOfCoolThings)
<console>:15: error: type mismatch;
 found   : BoxOfThings[OtherThing]
 required: BoxOfThings[Thing]
Note: OtherThing <: Thing, but class BoxOfThings is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
              new TypedPairOfBoxes(boxOfOtherThings, anotherBoxOfCoolThings)
                                   ^
<console>:15: error: type mismatch;
 found   : BoxOfThings[CoolThing]
 required: BoxOfThings[Thing]
Note: CoolThing <: Thing, but class BoxOfThings is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
              new TypedPairOfBoxes(boxOfOtherThings, anotherBoxOfCoolThings)
                                                     ^

scala> new TypedPairOfBoxes(boxOfCoolThings, anotherBoxOfCoolThings)
res3: TypedPairOfBoxes[CoolThing] = TypedPairOfBoxes@2f5e1167