鉴于此代码:
trait S {
def s: String
}
trait I {
def i: Int
}
case class CC_S(s: String) extends S
case class CC_I(i: Int) extends I
case class CC_S_I(s: String, i: Int) extends S with I
def combine(s: S, i: I): S with I = CC_S_I(s.s, i.i)
此测试成功:
Assert.assertEquals(CC_S_I("s", 1), combine(CC_S("s"), CC_I(1)))
(如何)我可以将 combine 方法泛型为具有类型参数的特征吗?即我想定义这样的东西:
trait MyTrait[A,B] {
def combine(a: A, b: B): A with B
}
这样我就可以像这样使用它:
class MyClass[A <: CC_S, B <: CC_I] extends MyTrait[A,B] {
override def combine(s: A, i: B) = CC_S_I(s.s, i.i) //Note: this line does not compile...
}
Assert.assertEquals(CC_S_I("s", 1), new MyClass().combine(CC_S("s"), CC_I(1)))
更新。这将是一个更好的例子:
class MyClass[A <: S, B <: I] extends MyTrait[A,B] {
override def combine(s: A, i: B) = CC_S_I(s.s, i.i) //Note: this line does not compile...
}
请参阅 Travis 的答案下的评论以查看答案。