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. This is an incredibly powerful way to design loosely coupled code. And we never ever have to fear the dreaded diamond rearing its head.