Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 80 ]

Groovy adds two additional new methods to lists: any and every. These return
a Boolean value if any or every member of the list, respectively, satisfies the
given closure:


given:
def list = [1,2,3,5,7,9]
expect: "any member is even because 2 is even"
list.any { it % 2 == 0 }
and: "every member is not even"
! list.every { it % 2 == 0 }

Maps

Groovy provides a map literal syntax as well. The declaration syntax for maps is
very similar to that of lists. We declare a map as a list of key-value pairs delimited
by colons. Groovy is flexible in what type of objects can be used as keys or values.
In principal, any object that has a hashCode function that returns consistent values
can be used as either a key or value in a map. By consistent, I mean that any specific
value that we define for the object will always return the same hashCode value. Let's
start by looking at maps by using strings as keys.


The first thing we can try is accessing a property. We can access an element of a Map
using both array style and property access:


given: "we declare a simple map"
def fruitPrices = ["apple":20,"orange":25,"pear":30]
expect: "we can subscript a map with any key value"
fruitPrices["apple"] == 20
and: "use the key like it was a property"
fruitPrices.apple == 20

We can also access elements of the Map using the get method directly:


expect: "we can retrieve a value using the get method"
fruitPrices.get("apple") == 20
and: "we can supply a default value for items that are not found"
fruitPrices.get("grape", 5) == 5

Empty maps can be declared as [:] this creates an empty Map that can be added
to later:


given: "we can declare a variable that is empty but is a map"
def empty = [:]
expect: "it is an empty map"
empty instanceof Map
empty.size() == 0

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