Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 5

[ 87 ]

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:


one


three


two


four


Let's dig a bit deeper into the structure of each of the calls shown in the preceding
code. We refer to each as a call because that's what it is—a method call. Groovy
augments the standard JDK with numerous helper methods. This new and improved
JDK is referred to as the Groovy JDK, or GDK for short. In the GDK, Groovy adds the
each method to the java.lang.Object class. We will discover later in this book how
to inject methods into existing classes ourselves. The signature of the each method is
as follows:


Object each(Closure closure)
Free download pdf