Introduction

In its most basic use, a Scala trait is just like a Java interface. When you’re faced with situations where you would have used an interface in Java, just think “trait” in Scala.

Just as Java classes can implement multiple interfaces, Scala classes can extend multiple traits. As you’ll see in the recipes in this chapter, this is done with the extends and with keywords, so when a class (or object) extends multiple traits, you’ll see code like this:

class Woodpecker extends Bird with TreeScaling with Pecking

However, using traits as interfaces only scratches the surface of what they can do. Traits have much more power than Java interfaces because, just like abstract methods in Java, they can also have implemented methods. However, unlike Java’s abstract classes, you can mix more than one trait into a class, and a trait can also control what classes it can be mixed into.

This chapter provides examples of the many uses of Scala traits.

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.