FAQ - Closures Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Closures

What problem do closures solve? Why have closures?

At one level they just allow internal iterators instead of external ones. This alone is really nice because looping is a lot cleaner. With Iterators for example you do all the work, because if you want to execute the loop of the body, you have to take responsibility for hasNext() and next().

So its basically providing the body of a loop or a callback etc which

will execute within the original scope.

Anonymous classes can seem like they are in fact closures, but they have limitations that cause annoying things like having to declare all your variables as final. The compiler just creates a synthetic constructor that takes any variables you are going to reference.

For me the main benefit of closures is that they allow you to write code for collections with a lot less boilerplate.

 

Search

Results of your search request can come from various sources: the Groovy website itself, the JIRA issues, the API documentation, as well as a few other interesting Groovy-related blogs.

  By  -  pages  -  views  - last modified