One typeclass derivation to rule them all: XML parsing using Dotty's typeclass derivation.

By Leandro Bolivar

Elevator Pitch

To some intermediate Scala programmers, macros were a source of witchcraft. Typeclass derivation, one of the most powerful functionalities, relied on macros. I want to show you that with dotty’s native derivation support we can all start coding our type class derivations without using the dark arts.

Description

Historically in Java, parsing XML has mostly relied on reflection calls and not so much in the type system. The errors with parsing data types from and to XML were discovered in runtime instead of compile time. Thanks to the Scala type system we can rely on the compiler to guarantee we have every modeled data type covered for our encoding/decoding purposes with the help of typeclass derivation. In Scala 2 we had to rely on experts of the dark arts of macros to provide a way for us mortals to derive typeclasses for products and coproducts so we could implement our libraries. Now comes the age of Dotty which makes our lives easier with its native typeclass derivation support.

Inspired mostly by what libraries like Circe have done with JSON, we will come up with a solution for parsing XML files without verbose hastle. No deep understanding of the inner workings for the new derivation capabilities is required, we will have a very pragmatical dive into the know how of typeclass derivation.

Notes

I have been an enthusiast of implementations that relied on typeclass derivation since shapeless brought up the idea and we saw it being used in libraries like circe. I ended up implementing a general purpose xml parser for production use, first using shapeless and then magnolia (shapeless had compiling performance issues when dealing with case classes with more that 30 attributes). I want to share the lessons learned and point out how dotty’s new derivation capabilities will actually make library creators’ life easier.

  • Basic familiarity with Dotty’s new features.
  • Scala Typeclass basic knowledge.