用mixin特性丰富对象

时间:2016-07-15 10:17:49

标签: scala traits

我有以下结构:

trait Runner {
  def run: Unit
}

trait LoggableRunner extends Runner {
  abstract override def run {
    println("logging enter")
    super.run
    println("logging exit")
  }
}

class RealRunner extends Runner {
  def run = println("running...")
}

这样我就可以通过以下方式记录我的课程:

val a = new RealRunner with LoggableRunner

在运行run方法之前和之后添加日志信息。

现在我真正想要的是能够用特征组成scala对象。我尝试过同样的方式:

object RealRunner extends LoggableRunner{
  def run = println("running...")
}

但我明白了:method run needs override modifier

所以我试过了:

 object RealRunner extends LoggableRunner{
      override def run = println("running...")
    }

但我明白了:method run needs abstract override modifiers。所以我再次尝试添加摘要,我得到了:abstract override modifier only allowed for members of traits

甚至可以将特征混合到物体中吗?

1 个答案:

答案 0 :(得分:1)

我不确定为什么它会这样行事(确实看起来确实很奇怪和令人困惑,希望,有更多线索的人会介入,并在此基础上阐明理由),但这里是你如何做你想做的事情:

trait Runner {
  def run = () // making it non-abstract, makes things a lot easier!
}

trait LoggableRunner extends Runner {
  override def run = { 
      println("start")
      super.run
      println("stop")
  }
  def foo = "foo"
}

trait RealRunner extends Runner { self: LoggableRunner => 
   override def run = println(foo) // uses things from LoggableRunner
}

object RealRunner extends RealRunner with LoggableRunner 

scala> RealRunner.run
start
foo
stop

宇呼!