O'Reilly logo

Groovy 2 Cookbook by Luciano Fiandesio, Andrey Adamovich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required