Closures as method parameters
We already know that parentheses around method parameters are optional, so the previous call to each
can also be considered equivalent to:
flintstones.each ({ println "Hello, ${it}")
Groovy has special handling for methods whose last parameter is a closure. When invoking these methods, the closure can be defined anonymously after the method call parentheses. So, yet another legitimate way to call the preceding line is:
flintstones.each() { println "hello, ${it}" }
The general convention is not to use parentheses unless there are parameters in addition to the closure:
given: def flintstones = ["Fred", "Barney", "Wilma"] when: "we call findIndexOf passing int and a Closure" def result = flintstones.findIndexOf(0) { it == 'Wilma'} then: result == 2
The signature of the GDK findIndexOf
method is:
int findIndexOf(int, Closure)
We can define our own methods that accept closures as parameters. The simplest case is a method that accepts only a single closure as...