在这个简化的实验中,我希望能够快速构建一个具有可堆叠特征的类,该类可以报告用于构建它的特征。这让我想起了装饰器模式,但我更愿意在编译时而不是在运行时实现它。
使用冗余代码的工作示例
class TraitTest {
def report(d: Int) : Unit = {
println(s"At depth $d, we've reached the end of our recursion")
}
}
trait Moo extends TraitTest {
private def sound = "Moo"
override def report(d: Int) : Unit = {
println(s"At depth $d, I make the sound '$sound'")
super.report(d+1)
}
}
trait Quack extends TraitTest {
private def sound = "Quack"
override def report(d: Int) : Unit = {
println(s"At depth $d, I make the sound '$sound'")
super.report(d+1)
}
}
然后执行(new TraitTest with Moo with Quack).report(0)
将报告:
> At depth 0, I make the sound 'Quack'
At depth 1, I make the sound 'Moo'
At depth 2, we've reached the end of our recursion
不幸的是,那里有很多冗余代码让我眼花缭乱。我清理它的尝试导致我:
没有冗余代码的非工作示例
class TraitTest {
def report(d: Int) : Unit = {
println(s"At depth $d, we've reached the end of our recursion")
}
}
abstract trait Reporter extends TraitTest {
def sound : String
override def report(d: Int) : Unit = {
println(s"At depth $d, I make the sound '${sound}'")
super.report(d+1)
}
}
trait Moo extends Reporter {
override def sound = "Moo"
}
trait Quack extends Reporter{
override def sound = "Quack"
}
当我们再次执行(new TraitTest with Moo with Quack).report(0)
时,我们现在看到:
> At depth 0, I make the sound 'Quack'
At depth 1, we've reached the end of our recursion
问题1: “Moo”的台词去哪儿了?
我猜 Scala 只看到override def report(d: Int)
一次,因此只将它放在继承链中一次。我抓住了稻草,但如果是这样的话,我该如何解决呢?
问题 2:每个具体性状如何提供独特的sound
?
解决第一个问题后,我会假设执行的结果(new TraitTest with Moo with Quack).report(0)
如下所示,因为继承是如何sound
工作的。
> At depth 0, I make the sound 'Quack'
At depth 1, I make the sound 'Quack'
At depth 2, we've reached the end of our recursion
我们如何才能使每个特征都使用其sound
实现中指定的特征?