Wednesday, April 9, 2008

The new groovy mixins syntax

Today, I read this post to the groovy dev list and felt the strong urge to play with it. Now to use this, you'll need to compile the groovy code from the trunk in their subversion repository. Read the tutorial about how to build from source. To avoid the dreaded OutOfMemoryException, be sure to increase the amount of heap available to the JVM by doing: ANT_OPTS=-Xmx512m. Now the code.
 
class DeceptiveIntegerExt {
static def minus(int self, int other) {
self + other;
}
}

Integer.mixin DeceptiveIntegerExt

assert 5 - 5 == 10


Let's explain this code: First, I create my mixin class which I named DeceptiveIntegerExt for the sheer reason that the only purpose was to overload the subtraction operator and make it add the numbers. Then I add the mixin class to the Integer class; finally I assert that my mixin works as it should, and indeed it does. Albeit that this is a VERY simple example, but I wanted to play with it.

That's all for now.

No comments: