Stackable Modifications using Traits in Scala

In one of my previous post about Traits in Scala, I have pointed out one sentence that abstract classes and traits in Scala are Stackable. So what does that mean? Let me elaborate a bit on that part.Scala allows stackable modifications to any methods using classes and/or traits which means you can choose very specific behaviour by stacking classes and traits by mixing them together. When you stack new trait by overriding the same method over and over, you will get different or add-on behaviour to your method.

Let’s understand the same concept by a quite simple example.

We have a abstract class Pizza with two abstract methods price() and description() it is extended by its subclass VegDelightPizza, not the price and description of this Pizza is fixed but as a customer you can add new extra toppings, cheese as well as sauce. As you add extra things your price and description will change. So Let’s design our classes using stackable modifications.

Let’s execute above example using scalac and scala commands,

You can see in output that we can select any combination of traits and can stake them together.

This is same as decorator design pattern with below differences,

  • Decoration done on class level rather object level in decorator design pattern.
  • Stackable traits ExtraMozzarellaCheese, ExtraTomatoToppings and ExtraBlackOlives decorates core class (or trait) VegDelightPizza at compile time, similar thing is being done in decorator pattern at runtime while decorating the objects.

See, it was quite simple…..!!!!! Stay tuned for my upcoming posts on Scala 🙂


Leave a Reply

Notify of