Groovy & Grails: Closures and Collections
What Is a Closure
A closure is a block of code wrapped in curly braces that you can store in a variable and pass around. Closures capture the surrounding variables, so they behave like small functions that carry their own context. They are the heart of Groovy style.
def greet = { name ->
"Hello, ${name}"
}
println greet("Alex")The arrow separates the parameter list from the body, and the last expression becomes the return value automatically.
Collections Built In
Groovy defines lists, maps, and ranges with simple square and curly bracket literals.
def languages = ["Java", "Groovy", "Python"]
def scores = [java: 90, groovy: 85]
println languages[1]
println scores.groovyA list is an ordered sequence. A map pairs keys with values, and Groovy lets you access values with square brackets or with a dot and the key name.
The Collection Methods
The real power arrives with methods like each, collect, find, findAll, and sum. They replace most hand-written loops.
def numbers = [1, 2, 3, 4, 5]
def doubled = numbers.collect { it * 2 }
def evens = numbers.findAll { it % 2 == 0 }
def total = numbers.sum()
println doubled
println evens
println totalcollect transforms every element, findAll keeps the ones matching the condition, and sum adds them up. The result reads as a description of the outcome rather than a manual loop.
Closures in Action
Early returns inside closures are allowed, which is handy for classification style logic.
def sign = { value ->
if (value > 0) return "positive"
if (value < 0) return "negative"
return "zero"
}
println sign(5)
println sign(-3)Combining closures with collection methods turns several lines of looping into a readable pipeline, so teams write less code and misread less of it.
Key Points
- Closures are code blocks that capture context and act as functions.
- Lists and maps have compact literal syntax built into the language.
- collect and findAll replace transformation and filtering loops.
- Methods like sum and join make aggregation one line.