Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 81 ]

When assigning values to Map elements, we can use either the array superscript
syntax or property access syntax:


when: "assigning a value, it can be done via superscript"
fruitPrices['apple'] = 21
then: "the expected value was set"
fruitPrices['apple'] == 21
when: "we try the same with property access"
fruitPrices.apple = 22
then: "that also works"
fruitPrices['apple'] == 22
when: "assign a value to a key that does not exist"
fruitPrices.grape = 6
then: "a new item is added to the Map"
fruitPrices == [apple:22,orange:25,pear:30, grape:6]

Maps support the plus operator for adding maps together:


given:
def fruit = [apple:20, orange:25 ]
def veg = [pea:1, carrot:15]
expect: "we can add these Maps using plus"
fruit + veg == [apple:20, orange:25, pea:1, carrot:15]

and: "map equality is agnostic to order"
fruit + veg == [ pea:1, carrot:15, apple:20, orange:25]

The most common use of maps in Groovy is with String keys. When we use a
String as key, we can interchangeably use the key with or without quotes. We can
also look up the value by using the subscript operator, or by using the property
reference semantics. Because any object can be a key, this allows us to define some
unusual looking maps:


given:
def squares = [ 1:1, 2:4, 3.0:9]
expect:
squares[1] == 1
squares[2] == 4
squares[3.0] == 9

Here we see how we can use what seem to be primitive numeric values as keys.
Because Groovy autoboxes these primitives into their equivalent wrapper object and
these wrappers implement consistent hashCode methods, we can use them as keys.
Not only this, but we can mix the type of object that we use as a key.

Free download pdf