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 multiple traits to a class. We've used object in the example just because of the main
method. This would be similar to creating a class with no constructor parameters.
Tip
How to mix traits in?
Mixing traits into a class...