An example of stackable modifications in Scala

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

Lately 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.

This can be demonstrated 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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.