@BeanProperty instructs the Scala compiler to generate JavaBeans style getter/setters for the annotated property. The following byte code is produced when compiling this code with the Scala compiler
Groovy has no trouble implementing JavaBeans style properties with as few lines of code as possible
Sadly it is not the same for Scala's property access style, you would have to write those methods by hand. Clever metaclass tricks won't work here as the Groovy compiler will complain on an incomplete class if you do not write those methods. If only there was a way to instruct the Groovy compiler to generate bolierplate code... oh wait, but there is! since Groovy 1.6 we can make the compiler to do just that, by means of the powerful AST transformations framework. Guillaume wrote an excellent piece about what's new in Groovy 1.6 at InfoQ, AST transformations are covered in great detail. In any case Hamlet D'Arcy wrote a small tutorial on writing your own AST transformations. Now that you know the secret sauce let's revisit the Groovy implementation of the Output trait
Much better now! But the good news don't stop here, the @Scalify AST transformations will also take care of mapping the appropriate Groovy overloaded operators into their Scala counterparts (taking a hint again from Daniel -> Interop Between Java and Scala), so while you write this on the Groovy side
You will be able to make the following calls from the Scala side
This is the list of the currently supported operators
Operator | Groovy | Scala |
---|---|---|
+ | plus() | $plus() |
- | minus() | $minus() |
* | multiply() | $times() |
/ | div() | $div() |
% | mod() | $percent() |
^ | xor() | $up() |
& | and() | $amp() |
| | or() | $bar() |
** | power() | $times$times() |
<< | leftShift() | $less$less() |
>> | rightShift() | $greater$greater() |
- | negative() | unary_$minus() |
+ | positive() | unary_$plus() |
~ | bitwiseNegate() | unary_$tilde() |
You surely noticed that a constructor had to be defined, if you're expecting to be able to call the following then you'd be in for a surprise
It turns out that while the generated byte code for all Scala friendly methods is accurate, there is still a missing feature that only Scala classes compiled by the Scala compiler have, a class attributed named "Pickle". This particular class attribute holds additional information that the Scala compiler uses to do its magic, however you're still able to make the following non-idiomatic Scala calls
The last piece of the puzzle is figuring out a way to create a Pickle from a Groovy class using the AST transformation framework, if anyone knows how to accomplish such a feat (calling the pickler from regular Java/Groovy) then please get in touch.
Keep on Groovying/Scaling!
PD: this is not an April's fools post, honest!