Scala traits: Stackable modifications example in Scala

As a brief note today, here’s an example of stackable modifications using traits in Scala.

What is ‘super’ in Scala when you mix in traits?

I was curious about what super means when you mix Scala traits into a class or object. A simplified answer is that super refers to the last trait that’s mixed in, though I should be careful and note that this is an oversimplification.

You can demonstrate this in an example that uses both inheritance and mixins with traits. Given this combination of traits and classes:

trait Animal {
    def sleep = println("Animal::sleep")

class Bird extends Animal {
    override def sleep = super.sleep

trait CanFly extends Bird {
    override def sleep = println("CanFly::sleep")

trait Feathered extends Bird {
    override def sleep = println("Feathered::sleep")

you’ll see results like this when the traits are combined in different orders:

val bird1 = new Bird with Feathered with CanFly
bird1.sleep  //OUTPUT: CanFly::sleep

val bird2 = new Bird with CanFly with Feathered
bird2.sleep  //OUTPUT: Feathered::sleep

That’s all I’m going to write about this today, but if you want to learn more about stackable modifications, the Artima website has a good example and discussion.