You are previewing Programming Scala.

Programming Scala

Cover of Programming Scala by Dean Wampler... Published by O'Reilly Media, Inc.
  1. Programming Scala
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Foreword
    4. Preface
      1. Welcome to Programming Scala
      2. Conventions Used in This Book
      3. Using Code Examples
      4. Safari® Books Online
      5. How to Contact Us
      6. Acknowledgments
    5. 1. Zero to Sixty: Introducing Scala
      1. Why Scala?
      2. Installing Scala
      3. For More Information
      4. A Taste of Scala
      5. A Taste of Concurrency
      6. Recap and What’s Next
    6. 2. Type Less, Do More
      1. In This Chapter
      2. Semicolons
      3. Variable Declarations
      4. Method Declarations
      5. Inferring Type Information
      6. Literals
      7. Tuples
      8. Option, Some, and None: Avoiding nulls
      9. Organizing Code in Files and Namespaces
      10. Importing Types and Their Members
      11. Abstract Types And Parameterized Types
      12. Reserved Words
      13. Recap and What’s Next
    7. 3. Rounding Out the Essentials
      1. Operator? Operator?
      2. Methods Without Parentheses and Dots
      3. Domain-Specific Languages
      4. Scala if Statements
      5. Scala for Comprehensions
      6. Other Looping Constructs
      7. Conditional Operators
      8. Pattern Matching
      9. Enumerations
      10. Recap and What’s Next
    8. 4. Traits
      1. Introducing Traits
      2. Stackable Traits
      3. Constructing Traits
      4. Recap and What’s Next
    9. 5. Basic Object-Oriented Programming in Scala
      1. Class and Object Basics
      2. Parent Classes
      3. Constructors in Scala
      4. Nested Classes
      5. Visibility Rules
      6. Recap and What’s Next
    10. 6. Advanced Object-Oriented Programming In Scala
      1. Overriding Members of Classes and Traits
      2. Companion Objects
      3. Case Classes
      4. Equality of Objects
      5. Recap and What’s Next
    11. 7. The Scala Object System
      1. The Predef Object
      2. Classes and Objects: Where Are the Statics?
      3. Sealed Class Hierarchies
      4. The Scala Type Hierarchy
      5. Linearization of an Object’s Hierarchy
      6. Recap and What’s Next
    12. 8. Functional Programming in Scala
      1. What Is Functional Programming?
      2. Functional Programming in Scala
      3. Recursion
      4. Tail Calls and Tail-Call Optimization
      5. Functional Data Structures
      6. Traversing, Mapping, Filtering, Folding, and Reducing
      7. Pattern Matching
      8. Partial Functions
      9. Currying
      10. Implicits
      11. Implicit Function Parameters
      12. Call by Name, Call by Value
      13. Lazy Vals
      14. Recap: Functional Component Abstractions
    13. 9. Robust, Scalable Concurrency with Actors
      1. The Problems of Shared, Synchronized State
      2. Actors
      3. Actors in Scala
      4. Traditional Concurrency in Scala: Threading and Events
      5. Recap and What’s Next
    14. 10. Herding XML in Scala
      1. Reading XML
      2. Writing XML
      3. Recap and What’s Next
    15. 11. Domain-Specific Languages in Scala
      1. Internal DSLs
      2. External DSLs with Parser Combinators
      3. Recap and What’s Next
    16. 12. The Scala Type System
      1. Reflecting on Types
      2. Understanding Parameterized Types
      3. Variance Under Inheritance
      4. Type Bounds
      5. Nothing and Null
      6. Understanding Abstract Types
      7. Path-Dependent Types
      8. Value Types
      9. Self-Type Annotations
      10. Structural Types
      11. Existential Types
      12. Infinite Data Structures and Laziness
      13. Recap and What’s Next
    17. 13. Application Design
      1. Annotations
      2. Enumerations Versus Pattern Matching
      3. Thoughts On Annotations and Enumerations
      4. Using Nulls Versus Options
      5. Exceptions and the Alternatives
      6. Scalable Abstractions
      7. Effective Design of Traits
      8. Design Patterns
      9. Better Design with Design By Contract
      10. Recap and What’s Next
    18. 14. Scala Tools, Libraries, and IDE Support
      1. Command-Line Tools
      2. Build Tools
      3. Integration with IDEs
      4. Test-Driven Development in Scala
      5. Other Notable Scala Libraries and Tools
      6. Java Interoperability
      7. Java Library Interoperability
      8. Recap and What’s Next
    19. A. References
    20. Glossary
    21. Index
    22. About the Authors
    23. Colophon
    24. SPECIAL OFFER: Upgrade this ebook with O’Reilly

Chapter 4. Traits

Introducing Traits

Before we dive into object-oriented programming, there’s one more essential feature of Scala that you should get acquainted with: traits. Understanding the value of this feature requires a little backstory.

In Java, a class can implement an arbitrary number of interfaces. This model is very useful for declaring that a class exposes multiple abstractions. Unfortunately, it has one major drawback.

For many interfaces, much of the functionality can be implemented with boilerplate code that will be valid for all classes that use the interface. Java provides no built-in mechanism for defining and using such reusable code. Instead, Java programmers must use ad hoc conventions to reuse implementation code for a given interface. In the worst case, the developer just copies and pastes the same code into every class that needs it.

Often, the implementation of an interface has members that are unrelated (“orthogonal”) to the rest of the instance’s members. The term mixin is often used for such focused and potentially reusable parts of an instance that could be independently maintained.

Have a look at the following code for a button in a graphical user interface, which uses callbacks for “clicks”:

// code-examples/Traits/ui/button-callbacks.scala

package ui

class ButtonWithCallbacks(val label: String,
    val clickedCallbacks: List[() => Unit]) extends Widget {

  require(clickedCallbacks != null, "Callback list can't be null!")

  def this(label: String, clickedCallback: () => Unit) =
    this(label, List(clickedCallback))

  def this(label: String) = {
    this(label, Nil)
    println("Warning: button has no click callbacks!")

  def click() = {
    // ... logic to give the appearance of clicking a physical button ...
    clickedCallbacks.foreach(f => f())

There’s a lot going on here. The primary constructor takes a label argument and a list of callbacks that are invoked when the button’s click method is invoked. We’ll explore this class in greater detail in Chapter 5. For now, we want to focus on one particular problem. Not only does ButtonWithCallbacks handle behaviors essential to buttons (like clicking), it also handles notification of click events by invoking the callback functions. This goes against the Single Responsibility Principle (see [Martin2003]), a means to the design goal of separation of concerns. We would like to separate the button-specific logic from the callback logic, such that each logical component becomes simpler, more modular, and more reusable. The callback logic is a good example of a mixin.

This separation is difficult to do in Java, even if we define an interface for the callback behavior. We still have to embed the implementation code in the class somehow, compromising modularity. The only other alternative is to use a specialized tool like aspect-oriented programming (AOP; see [AOSD]), as implemented by AspectJ (see [AspectJ]), an extension of Java. AOP is primarily designed to separate the implementations of “pervasive” concerns that are repeated throughout an application. It seeks to modularize these concerns, yet enable the fine-grained “mixing” of their behaviors with other concerns, including the core domain logic of the application, either at build or runtime.

Traits As Mixins

Scala provides a complete mixin solution, called traits. In our example, we can define the callback abstraction in a trait, as in a Java interface, but we can also implement the abstraction in the trait (or a derived trait). We can declare classes that “mix in” the trait, much the way you can declare classes that implement an interface in Java. However, in Scala we can even mix in traits at the same time we create instances. That is, we don’t have to declare a class first that mixes in all the traits we want. So, Scala traits preserve separation of concerns while giving us the ability to compose behavior on demand.

If you come from a Java background, you can think of traits as interfaces with optional implementations. Or, if you prefer, you can think of traits as a “constrained” form of multiple inheritance. Other languages provide constructs that are similar to traits, such as modules in Ruby, for example.

Let’s use a trait to separate the callback handling from the button logic. We’ll generalize our approach a little bit. Callbacks are really a special case of the Observer Pattern (see [GOF1995]). So, let’s create a trait that implements this pattern, and then use it to handle callback behavior. To simplify things, we’ll start with a single callback that counts the number of button clicks.

First, let’s define a simple Button class:

// code-examples/Traits/ui/button.scala

package ui

class Button(val label: String) extends Widget {
  def click() = {
    // Logic to give the appearance of clicking a button...

Here is the parent class, Widget:

// code-examples/Traits/ui/widget.scala

package ui

abstract class Widget

The logic for managing callbacks (i.e., the clickedCallbacks list) is omitted, as are the two auxiliary constructors. Only the button’s label field and click method remain. The click method now only cares about the visual appearance of a “physical” button being clicked. Button has only one concern, handling the “essence” of being a button.

Here is a trait that implements the logic of the Observer Pattern:

// code-examples/Traits/observer/observer.scala

package observer

trait Subject {
  type Observer = { def receiveUpdate(subject: Any) }

  private var observers = List[Observer]()
  def addObserver(observer:Observer) = observers ::= observer
  def notifyObservers = observers foreach (_.receiveUpdate(this))

Except for the trait keyword, Subject looks like a normal class. Subject defines all the members it declares. Traits can declare abstract members, concrete members, or both, just as classes can (see Overriding Members of Classes and Traits for more details). Also like classes, traits can contain nested trait and class definitions, and classes can contain nested trait definitions.

The first line defines a type for an Observer. This is a structural type of the form { def receiveUpdate(subject:Any) }. Structural types specify only the structure a type must support; you could think of them as “anonymous” types.

In this case, the structural type is defined by a method with a particular signature. Any type that has a method with this signature can be used as an observer. We’ll learn more about structural types in Chapter 12. If you’re wondering why we didn’t use Subject as the type of the argument, instead of Any, we’ll revisit that issue in Self-Type Annotations and Abstract Type Members.

The main thing to notice for now is how this structural type minimizes the coupling between the Subject trait and any potential users of the trait.


Subject is still coupled by the name of the method in Observer through the structural type, i.e., to a method named receiveUpdate. There are several ways we can reduce this remaining coupling. We’ll see how in Overriding Abstract Types.

Next, we declare a list of observers. We make it a var, rather than a val, because List is immutable, so we must create a new list when an observer is added using the addObserver method.

We’ll discuss Scala Lists more in The Scala Type Hierarchy and also in Chapter 8. For now, notice that addObserver uses the list cons “operator” method (::) to prepend an observer to the list of observers. The scala compiler is smart enough to turn the following statement:

observers ::= observer

into this statement:

observers = observer :: observers

Note that we wrote observer :: observers, with the existing observers list on the righthand side. Recall that any method that ends with : binds to the right. So, the previous statement is equivalent to the following statement:

observers = observers.::(observer)

The notifyObservers method iterates through the observers, using the foreach method and calls receiveUpdate on each one. (Note that we are using the “infix” operator notation instead of observers.foreach.) We use the placeholder _ to shorten the following expression:

(obs) => obs.receiveUpdate(this)

into this expression:


This expression is actually the body of an “anonymous function,” called a function literal in Scala. This is similar to a lambda and like constructs used in many other languages. Function literals and the related concept of a closure are discussed in Function Literals and Closures.

In Java, the foreach method would probably take an interface, and you would pass an instance of a class that implements the interface (e.g., the way Comparable is typically used).

In Scala, the List[A].foreach method expects an argument of type (A) => Unit, which is a function taking an instance of type A—where A represents the type of the elements of the list (Observer, in this case)—and returning Unit (like void in Java).


We chose to use a var with immutable Lists for the observers in this example. We could have used a val with a mutable type, like ListBuffer. That choice would make a little more sense for a real application, but we wanted to avoid the distraction of explaining new library classes.

Once again, we learned a lot of Scala from a small example. Now let’s put our Subject trait to use. Here is ObservableButton, which subclasses Button and mixes in Subject:

// code-examples/Traits/ui/observable-button.scala

package ui
import observer._

class ObservableButton(name: String) extends Button(name) with Subject {
  override def click() = {

We start by importing everything in the observer package, using the _ wildcard. Actually, we have only defined the Subject trait in the package.

The new class uses the with keyword to add the Subject trait to the class. ObservableButton overrides the click method. Using the super keyword (see Overriding Abstract and Concrete Methods), it first invokes the “superclass” method,, and then it notifies the observers. Since the new click method overrides Button’s concrete implementation, the override keyword is required.

The with keyword is analogous to Java’s implements keyword for interfaces. You can specify as many traits as you want, each with its own with keyword.

A class can extend a trait, and a trait can extend a class. In fact, our Widget class earlier could have been declared to be a trait.


If you declare a class that uses one or more traits and it doesn’t extend another class, you must use the extends keyword for the first trait listed.

If you don’t use extends for the first trait, e.g., you write the following:

class ObservableButton(name: String) with Button(name) with Subject {...}

You’ll get an error like this:

... error: ';' expected but 'with' found.
       class ObservableButton(name: String) with Button(name) with Subject {...}

The error should really say, “with found, but extends expected.”

To demonstrate this code, let’s start with a class for observing button clicks that simply counts the number of clicks:

// code-examples/Traits/ui/button-count-observer.scala

package ui
import observer._

class ButtonCountObserver {
  var count = 0
  def receiveUpdate(subject: Any) = count += 1

Finally, let’s write a test that exercises all these classes. We will use the Specs library (discussed in Specs) to write a Behavior-Driven Development ([BDD]) “specification” that exercises the combined Button and Subject types:

// code-examples/Traits/ui/button-observer-spec.scala

package ui
import org.specs._
import observer._

object ButtonObserverSpec extends Specification {
  "A Button Observer" should {
    "observe button clicks" in {
      val observableButton = new ObservableButton("Okay")
      val buttonObserver = new ButtonCountObserver

      for (i <- 1 to 3)
      buttonObserver.count mustEqual 3

If you downloaded the code examples from the O’Reilly site, you can follow the directions in its README files for building and running the examples in this chapter. The output of the specs “target” of the build should include the following text:

Specification "ButtonCountObserverSpec"
  A Button Observer should
  + observe button clicks

Total for specification "ButtonCountObserverSpec":
Finished in 0 second, 10 ms
1 example, 1 expectation, 0 failure, 0 error

Notice that the strings A Button Observer should and observe button clicks correspond to strings in the example. The output of a Specs run provides a nice summary of the requirements for the items being tested, assuming good choices were made for the strings.

The body of the test creates an “Okay” ObservableButton and a ButtonCountObserver, which gives the observer to the button. The button is clicked three times, using the for loop. The last line requires the observer’s count to equal 3. If you are accustomed to using an XUnit-style TDD tool, like JUnit (see [JUnit]) or ScalaTest (see [ScalaTestTool] and ScalaTest), then the last line is equivalent to the following JUnit assertion:

assertEquals(3, buttonObserver.count)


The Specs library (see Specs) and the ScalaTest library (see ScalaTest) both support Behavior-Driven Development ([BDD]), a style of Test-Driven Development ([TDD]) that emphasizes the “specification” role of tests.

Suppose we need only one ObservableButton instance? We actually don’t have to declare a class that subclasses Button with Subject. We can incorporate the trait when we create the instance.

The next example shows a revised Specs file that instantiates a Button with Subject mixed in as part of the declaration:

// code-examples/Traits/ui/button-observer-anon-spec.scala

package ui
import org.specs._
import observer._

object ButtonObserverAnonSpec extends Specification {
  "A Button Observer" should {
    "observe button clicks" in {
      val observableButton = new Button("Okay") with Subject {
        override def click() = {


      val buttonObserver = new ButtonCountObserver

      for (i <- 1 to 3)
      buttonObserver.count mustEqual 3

The revised declaration of observableButton actually creates an anonymous class in which we override the click method, as before. The main difference with creating anonymous classes in Java is that we can incorporate traits in this process. Java does not let you implement a new interface while instantiating a class.

Finally, note that the inheritance hierarchy for an instance can be complex if it mixes in traits that extend other traits, etc. We’ll discuss the details of the hierarchy in Linearization of an Object’s Hierarchy.

The best content for your career. Discover unlimited learning on demand for around $1/day.