Chapter 4Using Closures

We create anonymous inner classes in Java, where we define method arguments to register event handlers and provide short local glue code. Back when introduced in Java 1.1, anonymous inner classes seemed like a nice idea, but soon we realized that they become verbose, especially for really short implementations of single-method interfaces. Closures in Groovy are short anonymous methods that remove that verbosity.

Closures are lightweight, short, concise, and one of the features we’ll employ the most in Groovy. Where we used to pass instances of anonymous classes, now we can pass closures.

Closures are derived from the lambda expressions from functional programming, and “a lambda expression specifies the parameter and ...

Get Programming Groovy 2 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.