3

考虑这个例子:

abstract class Writer {
  def write(message: String): Unit
}

trait UpperCaseFilter extends Writer {
  abstract override def write(message: String) =
    super.write(message.toUpperCase)
}

trait LowerCaseFilter extends Writer {
  abstract override def write(message: String) =
    super.write(message.toLowerCase)
}

class StringWriter extends Writer {
  val sb = new StringBuilder

  override def write(message: String) =
    sb.append(message)

  override def toString = sb.toString
}

object Main extends App {
  val writer = new StringWriter with UpperCaseFilter with LowerCaseFilter
  writer.write("Hello, world!")
  println(writer)
}

我对“HELLO, WORLD!”的输出感到惊讶。为什么输出不是“你好,世界!” 还是编译错误?

4

1 回答 1

3

决定它的逻辑称为线性化。您可以在此处找到有关它的更多信息:

http://www.artima.com/pins1ed/traits.html#12.6

在您的情况下,整个类层次结构将像这样线性化:

LowerCaseFilter> UpperCaseFilter> Writer> StringWriter> AnyRef>Any

因此,如您所见,UpperCaseFilter是最后一次转换到StringWriter.

于 2014-07-03T20:08:25.053 回答