如何在具有冲突的抽象覆盖的多个特征混合时预测将选择哪个实现?

时间:2014-07-03 19:30:07

标签: scala mixins traits subtyping

考虑这个例子:

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!”感到惊讶。为什么输出不是“hello,world!”或编译错误?

1 个答案:

答案 0 :(得分:3)

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

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

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

LowerCaseFilter> UpperCaseFilter> Writer> StringWriter> AnyRef> Any

因此,正如您所看到的,UpperCaseFilter是转到StringWriter的最后一次转化。