Programming with Closures

We’re talking about the power and elegance of closures in this chapter, but first let’s discuss how to approach them in our projects. We need to decide whether we want to implement a certain functionality or task as a regular function/method or whether we should use a closure.

Closures augment, refine, or enhance another piece of code. For example, a closure may be useful to express a predicate or condition that will refine the selection of objects. We can use closures to take advantage of coroutines such as the control flow like in iterators or loops.

Closures are very helpful in two specific areas. They can help manage resource cleanup (see Using Closures for Resource Cleanup) and they can help create internal ...

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.