Understanding Groovy Closures: Definition, Usage, and List Operations
This article introduces Groovy closures, explaining their definition, implicit 'it' parameter, custom arguments, return behavior, and demonstrates how to assign, invoke, and pass closures to methods such as each() and findAll() for list processing, accompanied by practical code examples.
This article continues from the previous posts "From Java to Groovy Evolution" and "Groovy List", focusing on Groovy closures.
In Groovy, a closure is a block of code that can access variables and methods from its surrounding scope; it can be assigned to a variable and passed around like any other object.
Example of a simple closure:
def c = { println "hello" }
c()Closures have an implicit parameter named it, but you can also define explicit parameters. The last expression in a closure is its return value, though you may use the return keyword for clarity.
def square = { it * it }
assert square(3) == 9
def lengthThan = { String s, int i -> return s.size() > i }
assert lengthThan("FunTester", 4) == true
assert lengthThan("Fun", 6) == falseYou can pass closures to methods. The following log method accepts a Closure, measures execution time, and prints the result:
def log(Closure c) {
println "Calling closure"
def start = System.currentTimeMillis()
println "Result: " + c()
def end = System.currentTimeMillis()
println "Log success (time: ${end - start} ms)"
}
log({ return "Groovy is best language!" })
log { return "Groovy is best language!" }Using each(), a closure can be applied to every element of a list:
names.each({ String name -> println name })
names.each { String name -> println name }
names.each { println it }The findAll() method filters a collection based on a closure that returns a boolean, producing a new list of matching elements. Groovy also provides find(), every(), and any() for other common collection operations. def shortNames = names.findAll { it.size() <= 3 } Finally, the article shows how to rewrite a simple Java class in Groovy using closures and collection methods:
def names = ["Ted", "Fred", "Jed", "Ned"]
println names
def shortNames = names.findAll { it.size() <= 3 }
println shortNames.size()
shortNames.each { println it }Disclaimer: This content is original to "FunTester" and should not be reproduced by third parties without permission.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
