抱歉,标题有点含糊,很难将我的问题总结成一个单一的类。希望以下代码片段能更好地说明我的意图。
让我们开始为Reduceable
的所有事物引入特征:
trait Reduceable[A] {
def reduceWith(other: A): A
}
Reduceable
这样的例子可以作为计数器:
case class GenderCounter(male: Int, female: Int)
extends Reduceable[GenderCounter] {
override def reduceWith(other: GenderCounter): GenderCounter =
GenderCounter(male + other.male, female + other.female)
}
case class FruitCounter(apples: Int, oranges: Int)
extends Reduceable[FruitCounter] {
override def reduceWith(other: FruitCounter): FruitCounter =
FruitCounter(apples + other.apples, oranges + other.oranges)
}
GenderCounter(5, 10) reduceWith GenderCounter(4, 11)
// res: GenderCounter = GenderCounter(9,21)
以上述计数器作为参数的类本身也可以是Reduceable
case class CompoundCounter(c1: GenderCounter, c2: FruitCounter)
extends Reduceable[CompoundCounter] {
override def reduceWith(
other: CompoundCounter)
: CompoundCounter = CompoundCounter(
c1 reduceWith other.c1,
c2 reduceWith other.c2
)
}
CompoundCounter(GenderCounter(5, 10), FruitCounter(11, 2)) reduceWith CompoundCounter(GenderCounter(5, 10), FruitCounter(11, 2))
// res: CompoundCounter = CompoundCounter(GenderCounter(10,20),FruitCounter(22,4))
但是,当我尝试引入泛型Reduceable
类其参数也是泛型Reduceable
s
case class CollectionReduceable[A, B](r1: Reduceable[A], r2: Reduceable[B])
extends Reduceable[CollectionReduceable[A, B]] {
override def reduceWith(
other: CollectionReduceable[A, B])
: CollectionReduceable[A, B] = CollectionReduceable(
r1 reduceWith other.r1,
r2 reduceWith other.r2
)
}
// error: type mismatch
// found : other.r1.type (with underlying type Reduceable[A])
// required: A
// r1 reduceWith other.r1,
// Desired outcome: same as CompoundCounter
我得到了错误消息的来源-其原因是特征的reduceWith
签名要求other: A
,但是如果我更改它,则GenderCounter
和FruitCounter
将打破。我可以怎样改变才能达到预期的结果?谢谢!
答案 0 :(得分:4)
尝试
case class CollectionReduceable[A <: Reduceable[A], B <: Reduceable[B]](r1: A, r2: B) extends Reduceable[CollectionReduceable[A, B]] {
override def reduceWith(other: CollectionReduceable[A, B]): CollectionReduceable[A, B] =
CollectionReduceable(
r1.reduceWith(other.r1),
r2.reduceWith(other.r2)
)
}
CollectionReduceable(GenderCounter(5, 10), FruitCounter(11, 2)) reduceWith CollectionReduceable(GenderCounter(5, 10), FruitCounter(11, 2))
// CollectionReduceable(GenderCounter(10,20),FruitCounter(22,4))