synapse synapse - 2 months ago 18
Scala Question

Replacing delegation with cake

At the moment I'm stacking features on a class with delegation

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 { /* ... */ }


Is it possible to replace this code with something like this?

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

Answer

You just need to change Logging:

trait Logging extends Backend {
  abstract override def product(id: Int) = {
    println(s"get product $id")
    super.product(id)
  }
}
Comments