September 2015
Intermediate to advanced
250 pages
6h 40m
English
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 |
Read now
Unlock full access