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 Child with Debugger

This makes the log method available to the problemChild instance.