Closures as arguments
Groovy passes a closure like any other argument, and adds one rule that a build script uses on every line: a closure after the parentheses is the last argument.
The last argument
last.groovy
def repeat(int times, Closure block) {
times.times { block(it) }
}
repeat(3) { println "call ${it}" }
def twice(Closure<Integer> block, int value) {
block(value) * 2
}
println twice({ int n -> n + 1 }, 5)
println twice({ int n -> n * 10 }, 5)
groovy last.groovy
call 0
call 1
call 2
12
100
The closure outside the parentheses is the last argument, so repeat(3) { } and repeat(3, { }) are the same call. When the closure is not last, it keeps its parentheses.
A method that returns a closure
factory.groovy
def multiplier(int factor) {
{ int n -> n * factor }
}
def triple = multiplier(3)
def tenTimes = multiplier(10)
println triple(7)
println tenTimes(7)
println [1, 2, 3].collect(triple)
groovy factory.groovy
21
70
Caught: groovy.lang.MissingPropertyException: No such property: println for class: factory
groovy.lang.MissingPropertyException: No such property: println for class: factory
at factory.run(factory.groovy:10)
exit status: 1
The closure captures factor when the method runs, so each call returns a closure with its own value. That is a factory of functions with no class and no interface.
A lambda and a method pointer
lambda.groovy
def square = (int n) -> { n * n }
println square(6)
def shout = (String text) -> { text.toUpperCase() }
println shout('groovy')
def upper = 'ada'.&toUpperCase
println upper()
groovy lambda.groovy
36
GROOVY
ADA
Groovy 3 added the Java lambda syntax, and here it builds the same Closure: the braces are still required for the body, so a one-expression lambda is a closure with a block. A method pointer object.&method is a closure over that method, which is how a reference to a method is passed where a block is expected.
A plain closure is the Groovy form and works with every GDK method; the arrow form is worth knowing when a Java API takes a functional interface, because Groovy converts a closure to one automatically.
Related
- Closures, it and parameters: the parameter list these examples use.
- The GDK methods: the closures they take.
Article author: Arthur Isaev