O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required