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).
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.
If a trait method is not implemented inside the trait body and the class we are mixing it into is not abstract, the class will have to implement the trait. Otherwise, a compilation error will occur.