Chapter 6. Traits and Enums

Because traits and enums are fundamental building blocks of large Scala applications, they’re covered here in this second Domain Modeling chapter.

Traits can be used to define granular units of behavior, and then those granular units can be combined to build larger components. As shown in Recipe 6.1, in their most basic use, they can be used like a pre-Java 8 interface, where the primary reason you use them is to declare the signatures for abstract methods that extending classes must implement.

However, Scala traits are much more powerful and flexible than this, and you can use them to define concrete methods and fields in addition to abstract members. Classes and objects can then “mix in” multiple traits. These features are demonstrated in Recipe 6.2, Recipe 6.3, and Recipe 6.4.

As a quick demonstration of this approach, rather than attempt to define everything a dog can do in a single Dog class, Scala lets you define traits for smaller units of functionality like a tail, legs, eyes, ears, nose, and a mouth. Those smaller units are easier to think about, create, test, and use, and they can later be combined together to create a complete dog:

class Dog extends Tail, Legs, Ears, Mouth, RubberyNose

That’s a very limited introduction to what Scala traits can do. Additional features include:

Get Scala Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.