Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 82 ]

We also can use object values as keys, but in order to do so, we need to add
parentheses around them to assist the compiler in determining our intention.
In the following code, we add two keys to the map. The first key is a string, apple,
but the second is the value contained in the apple local variable, which is 1 :


given:
def apple = 1
def map = [ apple:"Red", (apple):"Green"]
then:
map[1] == "Green"
map["apple"] == "Red"

Operators


Groovy implements all of the usual operators that we expect from Java, and adds a
number of unique operators of its own. We have already encountered some of these
in the preceding sections, such as the spaceship operator (<=>), the Elvis operator
(? :), the manual type coercion operator (as) and the regex match (==~), find (=~),
and pattern operators (~).


Spread and spread-dot

Collections also support some useful operators such as the spread-dot operator (*.).
Spread-dot is used when we need to apply a method call or make a field or property
accessible across all members of a collection. This is best illustrated with some
examples, as shown in the following code:


given: "a map and two arrays with the same keys and values"
def map = [a:"apple", o:"orange", p:"pear"]
def keys = ["a", "o", "p"]
def values = ["apple", "orange", "pear"]
expect: "we can use spread dot to access all keys/values"
map*.key == keys
map*.value == values
and: "which is equivalent to using the collect method"
map.collect { it.key } == keys
map.collect { it.value } == values

We can use spread-dot to invoke a method across all members of a list:


class Name {
def name
def greet(greeting) {
println greeting + " " + name
}
}

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