Primary menu

Macro Annotations are a new type of macros, which are one of the candidates for inclusion (see also comment by Eugene below) in the upcoming Scala 2.11 release. However, thanks to the recently released Macro Paradise Scala 2.10 compiler plugin, with an extra option in the compiler/SBT settings, you can use them today, while still using a stable Scala version at runtime.

One of the Macro Annotations use-cases mentioned in the manual is compile-time AOP. I decided to try implementing something similar, but a bit simpler for a start: automatic generation of delegate methods (decorator pattern/proxy pattern). In fact, some years ago there was a similar effort using a compiler plugin (autoproxy plugin). As an additional motivation, Łukasz recently asked on our technical room if Scala has this exact functionality – instead of saying “No”, I should have said “Not yet” ;).

The results of the POC are available on GitHub, in the scala-macro-aop repository: https://github.com/adamw/scala-macro-aop. If you have SBT, you can play with the implementation just by invoking run from the SBT console.

How does it work? Let’s say we have an interface Foo with three methods (with very original names: method1, method2 and method3), each taking some parameters. We have a default implementation:

As the implementation is just a POC, it will only work in simple cases, that is for methods with a single parameter list, without type parameters and when the method is not overloaded. Plus the code of the macro is, let’s say, “not yet polished” ;).