Type-safe dynamic beans factory with Scala 2.10 macros + Dynamic

With Scala 2.10.0 just out, we’ve now got a couple of shiny new toys:

  • Macros provide a clean (but experimental) way to plug into the Scala compiler, making AST rewrites very easy and mostly type-safe.
  • Dynamic is a type that lets you hijack method calls to predefined “fallback” methods (applyDynamic and al.).

The very interesting thing here is that despite its name, Dynamic only involves compile-time routing of unknown methods… and it is possible to implement applyDynamic using a macro!

This means using Dynamic you can create DSLs with code that is loosely typed (in Scala type system terms) and with macros we can still add your own custom compilation-time type-checks, and even rewrite the code so that it no longer refers to Dynamic at the first place!

Some practice: a type-safe dynamic beans factory

Java Beans are a bit tedious to create from Scala:

Well, with a Dynamic subclass that implements applyDynamicNamed using a macro, we can reach the following syntax:

And of course, this is all type-checked and rewritten to the exact same setter-intensive code as above, with the exact same runtime performance (nifty, isn’t it?).

Enjoy! (see newest sources and tests in Scalaxy’s repository)

This entry was posted in Uncategorized. Bookmark the permalink.