I’ve been working with some of Groovy’s more powerful concepts lately and thought I would share some of the stuff I’ve discovered that is not readily apparent in the documentation. I myself took Groovy closures for granted for a while but once you really start to understand how powerful and flexible they are you can really start to code what would otherwise be mind-boggling concepts in vanilla Java.
Take the following example code for instance:
All three examples illustrate the same concept: using a Groovy closure to call a method on and arbitrary string instance. You could of course be doing much more in that closure, but for purposes of illustration i’ll keep it simple.
What we’re doing in examples 1 and 2 is changing the scope that the closure gets evaluated under. Normally, a delegate will resolve this to the scope that it was defined in. By setting the resolveStrategy and delegate, we tell it to look for a delegate first and resolve this to the delegate object. The delegate can be any Groovy/Java object. In doing so, when we invoke the closure, the split() method gets called on the splitMe object we assigned to delegate.
Example #2 is simply a Groovy convenience method for the same. You can either pass the closure as an argument or define it inline.
Example #3 probably looks familiar if you’ve ever used Groovy’s extensions to Object. By using Closure.call(), we can pass in an arbitrary number of arguments. Since we’re only passing in one, we gain the convenience of the untyped “it” property that you normally expect to be passed to a closure.
Closure.call() is an extremely powerful method that you can use to define your own Groovy iterator methods!
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.