More inheritance today, more specifically how to get help from the compiler in complex inheritance patterns
The example here is simple to illustrate the feature but imagine what it would look like in a much more complex project.
We saw multiple inheritance last time, but it can quickly become messy if a lot of yourtrait
are depending on each other.
It would be great if we could ask the compiler to remind us that two or more trait needs to always be together for the code to work well.
Well, guess what? It is !
It is possible in Scala to create atrait
that cannot be used if not mixed in with a selection of othertrait
. Let’s look at the syntax:
trait MyTrait { name: DependencyTrait => ... }
Thename
can be any variable name if you need to disambiguates two or more trait that might have same function names. It can also bethis
if you do not need an extra handler for it.
AndDependencyTrait
can be onetrait
that is required to createMyTrait
but it can more than one if you replace it bytrait1 with trait2 with trait3 ...
.
In case of failure to comply those constraint, the compiler will give you the following error:
illegal inheritance; self-type [Class you are working on] does not conform to [MyTrait]'s selftype [MyTrait] with [DependencyTrait]
You should have seen this error message in the exercise and you now know how to fix it.
You also now know how to befriend the compiler and making sure you don’t forget a criticaltrait
in the mix for your classes.