Mixin compositions

Scala allows developers to extend many traits in a single class. This adds the possibility of achieving multiple inheritance and save a lot of efforts in code writing, which has to be performed in languages where extending many classes is not allowed. In this sub topic, we will show how traits can be mixed in a specific class or used to create anonymous classes with some specific functionality while writing our code.

Mixing traits in

First of all, let's modify the code from the last 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 it can be seen from the preceding code, we can add ...

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