【发布时间】:2013-07-06 06:27:09
【问题描述】:
在这个简化的实验中,我希望能够快速构建一个具有可堆叠特征的类,该类可以报告用于构建它的特征。这让我想起了装饰器模式,但我更愿意在编译时而不是在运行时实现它。
使用冗余代码的工作示例
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?
【问题讨论】:
标签: scala inheritance mixins traits