【发布时间】:2014-03-30 16:24:31
【问题描述】:
我有一个名为 Mutatable 的特性,它会吐出一个实现类的修改副本。我还有一个我想在它上面叠加的特征,称为 CostedMutatable,它可以跟踪这样做的成本。 applyMutation 方法返回一个选项,因为稍后我想在特定突变不适用的情况下返回 None。
一个仅适用于 Ints 的简单版本(并通过添加新数字“改变”它们)如下所示:
trait Mutatable[M] {
def applyMutation(mut : M) : Option[this.type]
}
trait CostedMutatable[M] extends Mutatable[M]{
var cost : Int = _
def getCostFor(mut : M): Int
abstract override def applyMutation(mut : M) : Option[this.type] = {
cost += getCostFor(mut)
applyMutation(mut)
}
}
object Example extends App {
case class Mutation(x: Int)
class Test(s: Int) extends Mutatable[Mutation] {
val start = s
override def applyMutation(mut: Mutation): Option[Test]
= Some(new Test(s+mut.x))
}
class CostTest(s: Int) extends Test(s) with CostedMutatable[Mutation] {
override def getCostFor(mut: Mutation): Int = 2
}
val testCost = new CostTest(5).cost
}
问题是,这不会编译。我在编译时收到以下错误:
Error:(23, 18) overriding method applyMutation in trait Mutatable of type (mut: Example.Mutation)Option[Test.this.type];
method applyMutation has incompatible type
override def applyMutation(mut: Mutation): Option[Test] = Some(new Test(s+mut.x))
^
除了编译器错误之外,我还想到另一个问题:我是否以正确的方式接近这个问题?我应该改用 F 有界类型吗? (我需要每个新的实现类从 applyMutation 返回具体实现类的新副本。)
提前致谢。
【问题讨论】: