Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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. It has some special properties like implicit variables and support for free variables (which we'll see later on). We'll ignore the nitty gritty details for now (see the formal definition if you want those) and look at some simple examples.

Simple Example

Code Block
def clos = { println "hello!" }

println "Executing the Closure:"
clos()                          //prints "hello!"

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:

Code Block

def localMethod() {
  def localVariable = new java.util.Date()
  return { println localVariable }
}

def clos = localMethod()

println "Executing the Closure:"
clos()                          //prints the date when "localVariable" was defined

Parameters

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

Code Block
def closprintSum = { a, b -> print a+b }
closprintSum( 5, 7 )                       //prints "12"

The -> token is optional and may be omitted if your Closure definition takes fewer than two parameters.

A Closure without -> , i.e. {} , is a Closure with one argument that is implicitly named as 'it'. (see the next section below for details) In some cases, you need to construct a Closure with zero arguments, e.g. using GString for templating, defining EMC Property etc. You have to explicity define your Closure as { -> } instead of just { }

varargs could be used as parameters, refer to the Formal Guide for details. A JavaScript-style dynamic args could be simulated, refer to the Informal Guide.

Free variables

Closures may refer to variables not listed in their parameter list. Such variables are referred to as "free" variables. They are "bound" to variables within the scope where they are defined:

Code Block

def myConst = 5
def addToConst = { num -> num + myConst }
println addToConst(10) // => 15

Or another example:

Code Block

def localMethod() {
  def localVariable = new java.util.Date()
  return { println localVariable }
}

def clos = localMethod()

println "Executing the Closure:"
clos()                          //prints the date when "localVariable" was defined

Implicit variables

Within a Groovy Closure, several variables are defined that have special meaning:

...