Closures in Depth

Site Admin · 11 Sep 2026 · 7 views

What are Closures?

Closures are one of Groovy's most powerful features. A closure is a block of code that can be assigned to a variable, passed as an argument, and executed later. They are similar to lambdas in other languages but more flexible.

Creating Closures

// Basic closure
def sayHello = { println "Hello!" }
sayHello()  // Hello!

// Closure with parameters
def greet = { name -> println "Hello, ${name}!" }
greet("Alice")  // Hello, Alice!

// Default parameter (it)
def doubled = { it * 2 }
println doubled(5)  // 10

Closures as Arguments

Closures are commonly passed to methods:

def numbers = [1, 2, 3, 4, 5]

// each takes a closure
numbers.each { println it }

// collect transforms each element
def squares = numbers.collect { it * it }
println squares  // [1, 4, 9, 16, 25]

// find returns first match
def first = numbers.find { it > 3 }
println first  // 4

Closure Delegation

Groovy closures have a unique delegation mechanism that allows methods to be called on the delegate:

def config = {
    server "localhost"
    port 8080
}

config.delegate = new ServerConfig()
config()

Closures vs Lambdas

While Java lambdas are limited to functional interfaces, Groovy closures can have multiple statements, don't need explicit types, and support delegation:

// Java lambda
Function<Integer, Integer> doubler = n -> n * 2;

// Groovy closure
def doubler = { it * 2 }

Key Points

  • Closures are blocks of code that can be passed and executed later.
  • The implicit it parameter is used for single-argument closures.
  • Closures support delegation for powerful DSL creation.
  • Groovy collections APIs use closures extensively.
  • Closures are more flexible than Java lambdas.
Share this post:

Comments (0)

Please login or register to comment.