Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Collections and Closures

Groovy Closures

Understand Groovy closures: syntax, the implicit it parameter, multiple and default parameters, calling closures, returning them, capturing variables and passing them to methods.

A closure is a block of code you can store in a variable, pass to a method, return from a method and run later. If you have used lambdas in Java or arrow functions in JavaScript, the idea is familiar, but Groovy closures are more powerful and are used everywhere: in loops over collections, in builders, in Gradle scripts, in tests. Understanding closures unlocks most of idiomatic Groovy.

Groovy closures cannot run on this site, so Groovy blocks are read-only. Java stand-ins with lambdas show the same logic in runnable form.

The syntax

A closure is code between braces, optionally with parameters before an arrow:

GROOVY
def sayHi = { println 'Hi!' }
def square = { n -> n * n }
def add = { a, b -> a + b }

sayHi()                  // Hi!
println square(6)        // 36
println add(2, 3)        // 5
println add.call(2, 3)   // 5   (call() is the long form)

Closures are objects of type groovy.lang.Closure. Calling sayHi() is shorthand for sayHi.call(). The value of the last expression is the closure's result; return is optional.

The implicit parameter it

A closure with no declared parameters that is called with one argument receives it as it:

GROOVY
def twice = { it * 2 }
println twice(21)                         // 42
println [1, 2, 3].collect { it * 10 }      // [10, 20, 30]

If you want a closure with no parameters at all, write the arrow with nothing before it: { -> println 'no params' }. A closure with explicit parameters never has an it.

When the closure is more than a line or two, give the parameter a name: { person -> ... } is easier to read than it.

Parameters: types, defaults, varargs

GROOVY
def greet = { String name, String greeting = 'Hello' -> "$greeting, $name!" }
println greet('Ada')              // Hello, Ada!
println greet('Ada', 'Welcome')   // Welcome, Ada!

def sum = { int... nums -> nums.sum() }
println sum(1, 2, 3)              // 6

Closures check arguments when called: passing the wrong number gives a MissingMethodException. For maps you can destructure automatically in iteration methods (see each on a map in Maps).

The Java stand-in below uses functional interfaces to do the same: store functions in variables, call them, and pass them around.

Java Java stand-in: functions as values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Passing closures to methods

When the last parameter of a method is a closure, you can write it after the parentheses. If it is the only argument, drop the parentheses entirely:

GROOVY
def repeat(int times, Closure body) {
    times.times { body(it) }
}

repeat(3) { i -> println "run $i" }        // closure outside the parentheses
[1, 2, 3].each { println it }              // no parentheses at all

This syntax is why Groovy code reads like a DSL: repositories { mavenCentral() } in Gradle is just a method call with a closure argument.

Closures capture variables

A closure can read and change local variables of the scope where it was created:

GROOVY
def total = 0
[1, 2, 3].each { total += it }
println total                    // 6

def counter() {
    int count = 0
    return { -> ++count }        // the closure keeps its own count alive
}
def next = counter()
println next()                   // 1
println next()                   // 2

The variable count lives on after counter() returns because the closure holds a reference to it. Each call to counter() creates a separate counter. This is the classic closure idea: a function packaged with its environment. Java lambdas can only capture variables that never change, so this stand-in uses an array holder to imitate it.

Java Java stand-in: a counter that remembers its state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Returning values and early exit

The last expression is the result. return leaves the closure only:

GROOVY
def classify = { n ->
    if (n < 0) return 'negative'
    n == 0 ? 'zero' : 'positive'
}
println classify(-4)     // negative

Inside each, a return therefore acts like continue. You cannot break out of a closure; use find, any, takeWhile, or a regular loop. Throwing an exception also stops everything.

Closure properties and methods

Closures have useful members:

GROOVY
def add = { int a, int b -> a + b }
println add.maximumNumberOfParameters    // 2
println add.parameterTypes                // [int, int]
println add.getClass().superclass.name    // groovy.lang.Closure

Other methods: curry, rcurry, ncurry, memoize, trampoline, compose (<< and >>), delegate, owner, thisObject and resolveStrategy. The next lesson, Closure Delegate and Currying, covers them.

Converting closures and method references

A closure can be coerced to a Java functional interface automatically, or explicitly with as:

GROOVY
Runnable r = { println 'running' }
r.run()
def cmp = { a, b -> a.length() <=> b.length() } as Comparator
println ['ccc', 'a', 'bb'].sort(false, cmp)      // [a, bb, ccc]

This means every Java API that takes a Runnable, Comparator, Callable or a lambda-compatible interface accepts a Groovy closure directly. A method pointer (obj.&method) becomes a closure too.

Closures as strategies

Because closures are values, you can keep a map of behaviors, a simple version of the strategy pattern:

GROOVY
def ops = [
    '+': { a, b -> a + b },
    '-': { a, b -> a - b },
    '*': { a, b -> a * b }
]
println ops['*'](6, 7)       // 42

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In { it * 2 }, what is it?

    When a closure declares no parameters, a single argument is available as the implicit parameter it.
  2. 2. How do you declare a closure that takes NO parameters at all (so it does not exist)?

    An empty parameter list before the arrow, { -> ... }, declares zero parameters.
  3. 3. What does return do inside a closure passed to each?

    A closure's return only leaves that call, so inside each it acts like continue.
  4. 4. Which statement about closure variable capture is true?

    Groovy closures hold references to outer variables, so changes are visible both inside and outside.

Summary

  • A closure is a block { params -> body } that is an object you can store, pass and call.
  • it is the implicit single parameter; { -> ... } declares none.
  • A trailing closure can sit after the parentheses, which creates DSL-style code.
  • Closures capture and may modify surrounding variables, keeping state alive.
  • return exits one closure call; use find or loops to stop early.

Next: Closure Delegate and Currying