Previous Entry Share Next Entry
The Stackable Trait Pattern
Time for a small Scala Burble of the Day.

NSTIW, in a discussion on the akka-user mailing list (I finally committed to getting involved in the Akka community, and unsurprisingly have immediately started making trouble). Somebody suggested a tweak to my code which appeared to involve a trait (Scala's interface-plus-implementation mixins that make the language so powerful) using super to call a method on the *child* class. I pointed out that that was wrong -- but it turns out not to have been as wrong as I thought.

Enter the Stackable Trait Pattern, which is surely one of Scala's cleverer ideas -- a typesafe, statically-compiled way for mixins to work together similarly to how they do in dynamic languages. Basically, you build your concrete object out of a base class and any number of traits. Those traits can work *together* in a highly pluggable way. In this model, "super" doesn't just mean "the superclass" as it does in most static languages; instead, when used in this way, it means "the previous version of this method in the mixin list". Hence the "stackable" -- each trait acts as a *modifier* on the method, in an order decided when you actually build the final object.

It's a subtlety, but a really useful one -- it means that you can basically create a library of legos, which can be assembled in different configurations simply by constructing your concrete object with your traits in the desired order of "inheritance". Neat...


Log in

No account? Create an account