O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Understanding Traits

A trait is a behavior that can be mixed into or assimilated into a class hierarchy. For example, to model a friend abstraction, we can mix a Friend trait into any class—Man, Woman, Dog, and so on—without having to inherit all those classes from a common base class.

To understand the benefits of traits, let’s design an example first without them. We’ll start with a class Human and make it friendly. In the simplest form, a friend is someone who listens. To support this abstraction, here is the listen method that we’d add to the Human class:

 
class​ Human(​val​ name: ​String​) {
 
def​ listen() = println(s​"Your friend $name is listening"​)
 
}
 
 
class​ Man(​override​ ​val​ name: ​String​) ​extends​ Human(name)
 
class

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required