closures appear intuitive to use but i'am still learning from tutorials and haven't used groovy to realise a task/project creatively without "swimmies" so far.
For deeper insight:
- what exactly are closures?
- when can they be used, when not?
- is there a rule of thumb to distinguish them from methods?
I found this link from one of the reply by Jon, may be useful for you.
Open Source leads to Open Mind
Joined: Mar 21, 2003
thanks a lot for the link, but i know these examples and as i wrote, i find closures quite intuitive to use.
My question was rather for a little deeper understanding of closures.
Would it be wrong to say, that they are a special notation for one?/some? anonymous?/dynamic? method(s), that every Groovy Object provides?
Joined: Oct 29, 2008
I'm also new to Grails and Groovy. I leave it to Jon & other experts to answer...
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].