What is a Closure?

A Groovy closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point.

Simple Example

Note that in the above example, "hello!" is printed when the closure is called, not when it is defined.

Closures may be "bound" to variables within the scope where they are defined:

Parameters

Closure parameters are listed before the ->, like so:

Implicit variables

Within a closure, a number of variables are defined that have special meaning:

It

If you have a closure that takes a single argument, you may omit the parameter definition of the closure, like so:

this, owner, and delegate

this : as in Java, this refers to the enclosing class where a Closure is definedowner : the enclosing object (this or a surrounding closuredelegate : by default the same as owner, but changeable for example in a builder or ExpandoMetaClass

Example:

Practical Uses for Closures

Groovy extends java.lang.Object with a number of methods that accept closures as arguments. See GDK Extensions to Object for practical uses for closures.