Scala's easy and breezy decorations – stackable modifications

As we know well by now, programming in Scala is super simple. Actually, this is one major use of traits, namely to modify the existing class methods of an object. I am just giving the new methods now. You can refer to the following sample code for a working example:

  abstract class Animal(val rating: Int) {
    def giveInoculation(): Unit  // abstract method
    def alreadyInoculated() : Boolean // abstract method
  }
  trait FilterOutAlreadyInoculated extends Animal {
    abstract override def giveInoculation(): Unit = // 1
      if (!alreadyInoculated())
        super.giveInoculation()
  }
  class Horse(rating: Int, var inoculated: Boolean = false) extends Animal(rating) with Walks with Ordered[Animal] {

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.