Defining code as data in Groovy
One of the things that attracted the Java crowd to Groovy has been the presence of closures in the language since its creation in 2003. Closures are a very powerful feature of Groovy and one of the most widely used. It is important to understand them well to take full advantage of the language. In this recipe, we will try to demonstrate the beauty that closures add to the language.
Getting ready
At its core, a closure is an anonymous block of code, such as:
{ -> }
The previous snippet is actually a closure without body. It is, in fact, an object of type groovy.lang.Closure
. As with every other object, a closure can be passed to other methods or even to other closures. However, a closure is also a method—a method with ...
Get Groovy 2 Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.