Scala multiple inheritance

We talked about inheritance in the past.

Let’s see how we can combine several trait together and what are the limitations.

For this episode, finish the exercise once and then go back and follow the extra instructions in the comments if you have time to learn more.

The keyword of the day is with.

This article is for scala 2.x, things are changing in scala 3.x but the concepts are still the same. At the time of this article, Scastie, which I use to render the exercise do not support Scala 3 yet so we are going to revisit those concept and the new syntaxes in the future.

We saw extends already, when we want to add one more trait to the mix, we use with for the one after the first one.

[case] class MyClass(args....) extends TRAIT1 with TRAIT2 with TRAIT3 .... {

}

If you have followed the extra instructions in the comments after you were done with the exercise, you noticed that trait and abstract class behave differently.

You have to put the abstract class in first position and you can only have one present. It can seems weird but in practice, it is rarely an issue since you can convert the abstract class to a trait very easily. You would just move the input arguments to the body of the class and make them methods with def.

You might have also noticed that you can mix two or more trait that have the same method(s) defined as long as they are identical. But it stops working if they have methods with the same name but different types.

And the last bits to keep in mind is when using defined type, you cannot use that has a shortcut to create larger trait. But you can use it in the position of type. Let me explain:

type FOO = A with B

// this do no work:
trait BAR extends FOO

// this works:
trait BAR extends A with B

// this works:
val f: FOO = ???

If you want to create bundle of trait, you can simply make a new trait

trait FOO extends A with B

trait BAR extends FOO

val f: FOO = new BAR {}

And that is it for mixing several trait and handle multiple inheritance. As always, if you have questions or feedbacks, jump on the Discord server ! See you there.

Reveal more information and clues
Load Exercise