A taste of the cake pattern
Scala provides a nice way to inject dependencies via a feature called self-annotation. This is useful to inject dependencies. Consider the giveInnoculation()
method in Animal
, as shown here:
object ScalaDepInj extends App { abstract class Animal(val rating: Int, var inoculated: Boolean = false) { def name(): String def alreadyInoculated() = inoculated def setInoculated(b: Boolean) = { inoculated = b } } trait Vet { // 1 def name(): String def inoculate(animal: Animal) = { println(""Innoculating "" + animal.name) } } trait ChoosyVet extends Vet { // 2 def alreadyInoculated(): Boolean abstract override def inoculate(animal: Animal) = { if (!alreadyInoculated()) // filter out already // inoculated animals println(""Innoculating "" + animal.name) } } trait Inoculate { this: Animal with Vet => // 3 def setInoculated(b: Boolean) def giveInoculation() = { ...