Scala constraint inheritance

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 your trait 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 a trait that cannot be used if not mixed in with a selection of other trait. Let’s look at the syntax:

trait MyTrait { name: DependencyTrait => 
    ...
}

The name can be any variable name if you need to disambiguates two or more trait that might have same function names. It can also be this if you do not need an extra handler for it.

And DependencyTrait can be one trait that is required to create MyTrait but it can more than one if you replace it by trait1 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 critical trait in the mix for your classes.

Reveal more information and clues
Load Exercise