2

I want to write a family of traits whose methods should log something and a Logger trait that should be implemented in concrete Loggers and it should only be possible to mix in the above traits when a Logger is mixed in as well. I only know that a trait can depend on a class, i.e. it can only be mixed into classes who have this class as super type. What can I do?

Sebastian Bechtel
  • 363
  • 1
  • 3
  • 12

1 Answers1

4

It sounds like you need self types e.g.

trait Logger {
  def log(msg: String): Unit
}

trait ConsoleLogger extends Logger {
  def log(msg: String): Unit = { println(msg) }
}

trait NeedsLogger { self: Logger =>
  def doSomething(): Unit = {
    self.log("about to do something...")
    self.log("it worked!")
  }
}

object Test extends NeedsLogger with ConsoleLogger {
}

Test.doSomething()
Lee
  • 142,018
  • 20
  • 234
  • 287