Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 78 ]

Range objects have two properties, to and from, that define their limits, as shown in
the following code:


given: "some ranges"
def numbers = 1..100
def letters = 'a'..'z'
expect: "range has to and from properties"
numbers.from == 1
numbers.to == 100
letters.from == 'a'
letters.to == 'z'

Ranges are implemented under the covers by the java.util.List class.
This means that all of the Java APIs that are available on a List object can
also be applied to a range:


and: "range is a java.util.List so we can use contains"
numbers.contains 2
numbers.contains 5

We can also use the in keyword as part of a predicate to test if a particular value is
contained within the range:


and: "we can use the in keyword with ranges"
5 in numbers

Lists

Groovy supports the notion of list literals. List declarations look like array
declarations in Java. Lists declared in this way are in fact java.util.List
objects. Let's prove the last statement that ranges are equivalent to lists:


given: "a range and the list equivalent"
def numberList = [1,2,3,4,5,6,7,8,9,10]
def numberRange = 1..10
expect: "they are equal"
numberList == numberRange

There are some useful list operators that we can use as shortcuts with lists, including
plus, minus, and left shift:


given: "a list within a list"
def multidimensional = [1,3,5,["apple","orange","pear"]]

expect: "we can add to lists together using the plus operator"

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