目前,我正在使用委派
的课程上堆叠功能trait Backend {
def product(id: Int): String
}
class MyBackend extends Backend {
def product(id: Int) = "My product"
}
class LoggingBackend(underlying: Backend) extends Backend {
override def product(id: Int) = {
println(s"get product $id")
underlying.product(id)
}
}
class CachingBackend(underlying: Backend) extends Backend { /* ... */ }
是否可以用这样的代码替换此代码?
trait Logging {
this : Backend =>
def product(id: Int) = {
println(s"get product $id")
/* Don't know what to write here */
}
}
class MyLoggingBackend extends MyBackend with Logging
答案 0 :(得分:3)
您只需要更改Logging
:
trait Logging extends Backend {
abstract override def product(id: Int) = {
println(s"get product $id")
super.product(id)
}
}