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 Recipes 6.2, 6.3, and 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:

  • Abstract and concrete fields (Recipe 6.2)

  • Abstract and concrete methods (Recipe 6.3)

  • Classes that can mix in multiple traits, as shown in Recipes 6.4 and 6.5

  • The ability to ...

Get Scala Cookbook, 2nd Edition 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.