Scala multiple inheritance

We talked about inheritance in the past.

Let's see how we can combine severaltraittogether 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 iswith.

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 sawextendsalready, when we want to add one moretraitto the mix, we usewithfor 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 thattraitandabstract classbehave differently.

You have to put theabstract classin 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 theabstract classto atraitvery easily. You would just move the input arguments to the body of theclassand make them methods withdef.

You might have also noticed that you can mix two or moretraitthat 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 largertrait. 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 oftrait, you can simply make a newtrait

trait FOO extends A with B trait BAR extends FOO val f: FOO = new BAR 

And that is it for mixing severaltraitand 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