Closures and collection methods
In the last chapter, we encountered Groovy lists and saw some of the iteration functions, such as the each
method:
def flintstones = ["Fred","Barney"] flintstones.each { println "Hello, ${it}" }
This looks like it could be a specialized control loop similar to a while
loop. In fact, it is a call to the each
method of Object
. The each
method takes a closure as one of its parameters, and everything between the curly braces {}
defines another anonymous closure.
Closures defined in this way can look quite similar to code blocks, but they are not the same. Code defined in a regular Java or Groovy style code block is executed as soon as it is encountered. With closures, the block of code defined in the curly braces is not executed until the call()
method of the closure is made:
println "one" def two = { println "two" } println "three" two.call() println "four"
This will print the following...