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!」という出力に驚きました。出力が「hello, world!」ではないのはなぜですか。またはコンパイルエラー?

4

1 に答える 1