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 ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.