8.8. Adding a Trait to an Object Instance

Problem

Rather than add a 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 print statement shown in its constructor.

Discussion

As a more practical matter, you might mix in something like a debugger or logging trait when constructing an 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.

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.