初始化scala中特征内的特征

时间:2012-12-05 07:46:26

标签: scala composition traits

Scala in Depth中有以下示例:

trait Logger {
  def log(category: String, msg: String) : Unit = {
       println(msg)
  }
}

trait DataAccess {
  def query[A](in: String) : A = {
     ...
  }
}

trait LoggedDataAccess {
  val logger = new Logger
  val dao = new DataAccess

  def query[A](in: String) : A = {
     logger.log("QUERY", in)

     dao.query(in)
  }
}

我对特性LoggedDataAccess中Logger和DataAccess的初始化感到有些困惑。在REPL中,当我输入此代码时,我得到以下异常:

 error: trait Logger is abstract; cannot be instantiated
       val logger = new Logger

特征是否可以像这样初始化?

1 个答案:

答案 0 :(得分:8)

Trait无法实例化,但您可以创建一个匿名的trait实现实例:

scala> trait Test
defined trait Test

scala> new Test
<console>:9: error: trait Test is abstract; cannot be instantiated
              new Test
              ^

scala> new Test{}
res0: Test = $anon$1@7fafd333

scala> new Object with Test
res1: Test = $anon$1@4fe11d82

new Test{}new Object with Test的含义相同。他们创建新的匿名类并立即实例化。