Structural Types: Less Magical, More Powerful
A busy day on the Dotty front, as another part of the Dotty design starts wending its way towards a SIP. Now under discussion: the new design for structural types.
A structural type, in the traditional sense, looks something like this:
type Foo = { val x; def bar(i: Int): String }
That is, it is declaring a type that is defined by its contents — this means “a type that happen to have x
and bar
". Any value that has both of those members can be assigned to a Foo
.
This is occasionally useful, but is pretty magical under the hood. It was originally implemented using reflection, so it’s rather slow on the JVM. And the reflection-based approach simply doesn’t work on JS or Native, so they had to implement their own special magic under the hood to support it.
The proposal at hand is to replace the magic with a new concept of Selectable
, a formal way of saying, “the members of this type are resolved dynamically”. This allows structural types to stop being compiler magic, and instead become a userland concept that you can use yourself.
In practice, the rewrite of structural types per se probably doesn’t matter too much for most folks — the code above will continue to work as it did before. (Although see the link for a few limitations of the new approach.)
What’s much more important is that you will now be able to use this yourself. The Dotty page on the subject discusses why this new tool is really powerful: it will make it much easier to define things like database-member access in a more natural way.
IMO, this one’s a huge win, likely one of those features that we’ll keep finding more and more uses for. The interface between Scala’s strongly-typed view of the world and runtime data has always been a point of subtle friction. By providing a formal, official way to interface between these two views, I expect we’ll be able to clean up a lot of real-world code, and build better libraries.
As always, if you’re interested in the topic, check out the links above, and chime in on the discussion…