by Rahel Lüthy
Suppose you have a simple class hierarchy with an API optimized for method chaining:
For obvious reasons, the compiler will only allow to chain methods in a certain order:
In the Java world, possible work-arounds involve generics. Either via overriding, or with a self-reference trick. Here’s how it would look in Scala:
While this works just fine, it involves quite some clutter. And Scala can actually do better! A powerful (but yet not very well-known) construct can solve the problem:
And now go spread the word!