Reputation: 363
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?
Upvotes: 2
Views: 869
Reputation: 144206
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()
Upvotes: 4