O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required