Scala Language Stackable Modification with Traits


You can use traits to modify methods of a class, using traits in stackable fashion.

The following example shows how traits can be stacked. The ordering of the traits are important. Using different order of traits, different behavior is achieved.

class Ball {
  def roll(ball : String) = println("Rolling : " + ball)

trait Red extends Ball {
  override def roll(ball : String) = super.roll("Red-" + ball)

trait Green extends Ball {
  override def roll(ball : String) = super.roll("Green-" + ball)

trait Shiny extends Ball {
  override def roll(ball : String) = super.roll("Shiny-" + ball)

object Balls {
  def main(args: Array[String]) {
    val ball1 = new Ball with Shiny with Red
    ball1.roll("Ball-1") // Rolling : Shiny-Red-Ball-1

    val ball2 = new Ball with Green with Shiny
    ball2.roll("Ball-2") // Rolling : Green-Shiny-Ball-2

Note that super is used to invoke roll() method in both the traits. Only in this way we can achieve stackable modification. In cases of stackable modification, method invocation order is determined by linearization rule.