Extending traits

Traits can also extend each other. Have a look at the following example:

trait Ping {  def ping(): Unit = {    System.out.println("ping")  }}trait Pong {  def pong(): Unit = {    System.out.println("pong")  }}trait PingPong extends Ping with Pong {  def pingPong(): Unit = {    ping()    pong()  }}object Runner extends PingPong {  def main(args: Array[String]): Unit = {    pingPong()  }}
The preceding example is simple and it should really just make the Runner object mix the two traits separately. Extending traits is useful in a design pattern called Stackable Traits, which we will be looking into later in this book.

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.