Dotty news: Automatic Typeclass Derivation

Mark "Justin" Waks
2 min readDec 10, 2018

--

I seem to have fallen into a role of “swallowing the firehose so you don’t have to”, so I’m going to continue pointing out cool stuff being discussed in the Dotty project.

Usual warning: this is highly experimental: not even merged to Dotty master, much less released. This is an early look at stuff that might happen.

Martin has a new PR in progress, exploring automatic typeclass derivation. Here’s the readme document, which is well worth a read if you’re interested in where things might go.

The tl;dr is that this document postulates a new bit of syntax that you can put onto a well-behaved ADT, like this:

enum Tree[T] derives Eq, Ordering, Pickling {
case Branch(left: Tree[T], right: Tree[T])
case Leaf(elem: T)
}

This is defining a Tree data type, with Branch and Leaf subtypes under it — that’s well-established Dotty by now. What is new is that derives bit, which basically says, “auto-generate implementations of the Eq, Ordering, and Pickling typeclasses for Tree and everything under it”.

The article then goes into a deep dive of how Eq might be implemented to make this possible. It shows off how to leverage a bunch of Dotty features (including both type matching and implicit matching) to set up the typeclass so that it will Just Work with ADTs. It leaves the other typeclasses as an exercise for the reader, but those seem like they ought to be straightforward variations of the technique shown here.

(NB: for the moment, this document is using “traditional” implicit syntax, since the possible new syntax for typeclass-oriented implicits is still very much under debate.)

It’s a very cool proof of concept — not the final word on the subject, but it helps build confidence that we can do Shapeless-like things using Dotty, using built-in tools that at least aren’t any more cryptic than doing them in modern Shapeless style.

Again, this is just early-stage experiments — lots is likely to change, and I hope that we can evolve a higher-level layer that reduces the boilerplate. But it’s exciting stuff, showing that Dotty is taking typeclasses seriously as a reasonably first-class concept in Scala, and that Shapeless-style magic is well within reach.

--

--

Mark "Justin" Waks
Mark "Justin" Waks

Written by Mark "Justin" Waks

Lifelong programmer and software architect, specializing in online social tools and (nowadays) Scala. Architect of Querki (“leading the small data revolution”).

No responses yet