Mixing traits in

First of all, let's modify the code from the previous example. It is a really simple change and it will also show exactly how traits can be mixed in:

object MixinRunner extends Ping with Pong {  def main(args: Array[String]): Unit = {    ping()    pong()  }}

As can be seen from the preceding code, we can add multiple traits to a class. We've used objects in the example just because of the main method. This would be similar to creating a class with no constructor parameters (objects in Scala are singleton classes).

How to mix traits in?

Mixing traits into a class is done with the following syntax: extends T1 with T2 with … with Tn. If a class already extends another class, we just keep on adding the traits using the with keyword. ...

Get Scala Design Patterns - Second 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.