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

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] {

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