Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 83 ]

given: "An array of Name objects"
def names = [ new Name(name:"Aaron"),
new Name(name:"Bruce"),
new Name(name:"Carol")]
when: "we invoke a method via spread dot"
names*.greet("Hello")
then: "the method is called in sequence across all the members"
"""Hello, Aaron
Hello, Bruce
Hello, Carol""" == output()

A close relative of spread-dot is the spread operator. Spread has the effect of tearing
a list apart into its constituent elements, as shown here:


and: "a closure that expects three parameters"
def greetAll = { a, b, c ->
println "Hello $a, $b and $c"
}
when: "we use spread against the names array"
greetAll(*names.name)
then: "It explodes the names array into three separate objects"
"Hello Arron, Bruce and Carol"

Null safe dereference

One of my favorite operators in Groovy is the null safe dereference operator.
How many times in your programming career with Java have you needed to
write the following?


Customer customer = getCustomerFromSomewhere();
if (customer != null) {
String name = customer.getName();
}

Groovy provides a neat (?.) operator that automatically does the null check for you
before dereferencing, so the preceding code can be written, as follows:


Customer customer = getCustomerFromSomewhere()
String name = customer?.name;

All told, these syntactical shortcuts make for much more concise and readable code.
Freed from the syntactical sugar of Java, we can write cleaner code more quickly.
Once you've gotten used to this shorthand, going back to Java is like wearing a pair
of lead boots.

Free download pdf