How to use Scala traits as simple mixins

This is an excerpt from the Scala Cookbook. This is Recipe 8.4, “How to use Scala traits as simple mixins (or, How to mix in Scala traits).”

Problem

You want to design a solution where multiple Scala traits can be mixed into a class to provide a robust design.

Solution

To implement a simple mixin in Scala, define the methods you want in your trait, then add the trait to your class using extends or with. For instance, the following code defines a Tail trait:

trait Tail {
    def wagTail { println("tail is wagging") }
    def stopTail { println("tail is stopped") }
}

You can use this trait with an abstract Pet class to create a Dog:

abstract class Pet (var name: String) {
    def speak // abstract
    def ownerIsHome { println("excited") }
    def jumpForJoy { println("jumping for joy") }
}

class Dog (name: String) extends Pet (name) with Tail {
    def speak { println("woof") }
    override def ownerIsHome {
        wagTail
        speak
    }
}

The Dog class extends the abstract class Pet and mixes in the Tail trait, and can use the methods defined by both Pet and Tail:

object Test extends App {
    val zeus = new Dog("Zeus")
    zeus.ownerIsHome
    zeus.jumpForJoy
}

In summary, the Dog class gets behavior from both the abstract Pet class and the Tail trait; this is something you can’t do in Java.

To see a great demonstration of the power of mixins, read Artima’s short “Stackable Trait Pattern” article. By defining traits and classes as base, core, and stackable components, they demonstrate how sixteen different classes can be derived from three traits by “stacking” the traits together.

See Also

When you develop traits, you may want to limit the classes they can be mixed into. The classes a trait can be mixed into can be limited using the following techniques:

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

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.
By submitting this form, you accept the Mollom privacy policy.