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 no associated class; therefore, it may have arguments and can return a value (yes, it can also return a closure). A closure always returns the value of the last statement in the body; the return
keyword is not needed. The body of a closure is not...