How to dynamically add a Scala trait to an object instance

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a very short recipe, Recipe 8.8, “How to dynamically add a Scala trait to an object instance.”

Problem

Rather than add a Scala trait to an entire class, you just want to add a trait to an object instance when the object is created.

Solution

Add the trait to the object when you construct it. This is demonstrated in a simple example:

class DavidBanner
trait Angry {
    println("You won't like me ...")
}

object Test extends App {
    val hulk = new DavidBanner with Angry
}

When you compile and run this code, it will print, “You won’t like me ...”, because the hulk object is created when the DavidBanner class is instantiated with the Angry trait, which has the println statement shown in its constructor.

Discussion

As a more practical matter, you might mix in something like a debugger or logging trait when constructing a Scala object to help debug that object:

trait Debugger {
    def log(message: String) {
        // do something with message
    }
}

// no debugger
val child = new Child

// debugger added as the object is created
val problemChild = new ProblemChild with Debugger

This makes the log method available to the problemChild instance.

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.