Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 70 ]

We can pass a closure as a method parameter. Many useful collection methods take a
closure as a parameter. The list each() method takes a closure as its parameters. The
each() method iterates over a list and applies the closure to each element in the list:


given: "a list of fruits"
def fruits = ["apple","orange","pear"]
and: "a closure that can operate on a single String"
def likeIt = {String fruit -> println "I like ${fruit}s"}
when: "we invoke the each method of list passing the closure"
fruits.each likeIt
then: "each element of the list is passed to the closure in turn"
"""I like apples
I like oranges
I like pears""" == output()

Now, if we look back at our matcher example, at the first glance, it seems to be using
some specialized collection iteration syntax:


matcher.each { match -> println match }

However, if we remember that matcher is a collection of matches, and that
parentheses in Groovy are optional, we can see that all that is happening here is that
a closure is passed to the each method of the matcher collection. We could have
written the same statement as:


matcher.each ({ match -> println match })

Groovy also has a neat shorthand for closures, which have just one parameter.
We don't need to explicitly name this parameter and can just refer to it as it.
So, our matcher statement can be even more succinct:


matcher.each { println it }

Control structures


Groovy supports the same logical branching structures as Java. The Groovy versions
of the common branching are identical in structure to those of Java:


// Simple if syntax
if (condition) {
}
// If else syntax
if (condition) {
} else {
}
// Nested if then else syntax

http://www.ebook3000.com
Free download pdf