Defeating the dreaded diamond

We saw that the diamond prevented us from reusing the code. In C++ though, you can use Multiple inheritance (MI), as it is sparingly used. In Java, you cannot use MI at all. In Scala, what happens when we mix in traits with two or more traits that have the same method? We saw earlier that the rightmost trait method gets called.

Here, there is an elaborate process, linearization, that flattens out the hierarchy. The process is described in all its nitty-gritty detail in the code labeled as 1. The mechanism effectively results in a single-method resolution. This avoids the method ambiguity, also known as, the dreaded diamond.

You get to reuse an implementation, add dependencies, and stack up behaviors in this method. ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.