考虑这个例子:
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!”或编译错误?
答案 0 :(得分:3)
决定它的逻辑称为线性化。您可以在此处找到有关它的更多信息:
http://www.artima.com/pins1ed/traits.html#12.6
在您的情况下,整个类层次结构将像这样线性化:
LowerCaseFilter
> UpperCaseFilter
> Writer
> StringWriter
> AnyRef
> Any
因此,正如您所看到的,UpperCaseFilter
是转到StringWriter
的最后一次转化。