Java Reference
In-Depth Information
}
assert capitalized == "I'm A Groovy Coder "
Note that unlike the for-each loop, the value variable is not declared to have a type: not
even def .
Still, none of those loops are the most common way of iterating in Groovy. Rather than
write an explicit loop, as in the previous examples, Groovy prefers a more direct imple-
mentation of the Iterator design pattern. Groovy adds the each method, which takes a
closure as an argument, to collections. The each method then applies the closure to each
element of the collection:
(0..5).each { println it }
Again, because the closure is the last argument of the method, it can be placed after the
parentheses. Because there are no other arguments to the each method, the parentheses
can be eliminated entirely.
Each
The each method is the most common looping construct in Groovy.
The Iterator design pattern recommends separating the way you walk through the elements
of a collection from what you plan to do with those elements. The each method does the
iterating internally. The user determines what to do with the elements by supplying a clos-
ure, as shown. Here the closure prints its argument. The each method supplies each value
in the range, one by one, to the closure, so the result is to print the numbers from zero to
five.
Like the for-in loop, inside the closure you have access to each element, but not to
the index. If you want the index, though, there's an additional method available called
eachWithIndex :
def strings = ['how','are','you']
def results = []
strings. eachWithIndex { s,i -> results << "$i:$s" }
assert results == ['0:how', '1:are', '2:you']
Search WWH ::




Custom Search