Hi Chris,
If you are comfortable with JavaScript functions you are well on your way to using closures. A closure is a first class object in Groovy, just as a function is a first class object in JavaScript. Closures can be anonymous or named:
In the first example we declare a list with the numbers 1, 2 and 3 as the contents, then use the collect method to execute an in-line closure for each item in the list and construct a new list from the result of each call to the in-line closure. The second example declares a closure and assigns it to the variable
doubleIt, the reference to the
doubleIt closure is then passed into the collect method to produce the same result.
The term closure actually refers to the scope that the code can access, here is a basic example where the closure is defined within a method, that can access a local variable declared in the same method:
Here is
an excellent post by Martin Fowler explaining closures, he uses ruby but the principles are the same. Also, his examples have been converted into Groovy code on the [url=http://groovy.codehaus.org/Martin+Fowler%27s+closure+examples+in+Groovy]Groovy site[/url].
Cheers,
Jon.