Returning the "Current" Type in Scala

From the article by tpolecat:

A common question on the #scala IRC channel is

I have a type hierarchy … how do I declare a supertype method that returns the “current” type?

This question comes up a lot because Scala encourages immutability, so methods that return a modified copy of this are quite common. Making the return type of such methods sufficiently precise is tricky, and is the subject of this article.

The closest thing to a “standard” approach (as seen in stdlib collections, for example) is to use an F-bounded type, which mostly works, but cannot fully enforce the constraint we’re after (it still takes some discipline and leaves room for error). Shout-out here to @nuttycom for his prior work exploring the pitfalls of this approach.

A better strategy is to use a typeclass, which solves the problem neatly and leaves little room for worry. In fact it’s worth considering abandoning subtype polymorphism altogether in these situations.

We will examine the problem and both solutions, and finish up by exploring heterogeneous collections of these beasties, which involves some pleasantly fancy types. But first let’s talk about…