3

In Scala in Depth there is this example:

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)
  }
}

I am a little confused by the initialization of Logger and DataAccess in the trait LoggedDataAccess. In the REPL, when I type out this code, I get the following exception:

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

Can a trait actually be initialized like that?

4

1 回答 1

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意思一样。他们创建新的匿名类并立即实例化它。

于 2012-12-05T08:03:11.213 回答