Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 77 ]

We can iterate all the values of a list without any funky Iterator objects:


for ( x in ["apple", "orange", "pear"])
println x

In fact, as we will see in the following section on collections, we can use the
in expression to iterate over any collection type. We can even iterate over the
characters in a string, as follows:


def hello = "Hello, World!"
for ( c in hello)
println c

Collections


Groovy has enhanced the Java collection classes by adding to, and improving on,
the declaration syntax and additional convenience methods. It also adds the new
collection type range, which provides a special-purpose syntax for managing ranges
of values.


Ranges

Groovy supports the concept of a range of values. We define a range of values with
the range operator (..). So, a range of integers from 1 to 10 is defined with 1..10. A
range value can be any object that belongs to a class that defines the previous() and
next() methods and implements the Comparable interface. We saw previously how
we can use the for (variable in range) style loop to iterate through a range.
We can define ranges that are inclusive or exclusive, as follows:


given: "an inclusive and exclusive range"
def inclusive = 1..10
def exclusive = 'a'..<'e'
when: "we collect all the possible values of that range"

def inclusiveValues = inclusive.collect { it }
def exclusiveValues = exclusive.collect { it }
then: "result is an inclusive/exclusive list of those values"
inclusiveValues == [1,2,3,4,5,6,7,8,9,10]
exclusiveValues == ['a','b','c','d']
Free download pdf