相关疑难解决方法(0)

可堆叠特征中的继承和代码重用

在这个简化的实验中,我希望能够快速构建一个具有可堆叠特征的类,该类可以报告用于构建它的特征.这让我想起了装饰器模式,但我更喜欢在编译时而不是在运行时实现它.

冗余代码的工作示例

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) …
Run Code Online (Sandbox Code Playgroud)

inheritance scala traits mixins

5
推荐指数
1
解决办法
1705
查看次数

标签 统计

inheritance ×1

mixins ×1

scala ×1

traits ×1