Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 56 ]

When method calls are nested, the parentheses are also needed to let the compiler
distinguish between the calls:


greeting = { name -> return "Hello, " + name }

// Parens are optional for println but required for nested
// greeting call
println greeting ( "Fergal" )

The optional dot in method chains

Version 1.8 of the Groovy language added another nice feature. When we chain
methods, the dot notation as well as the parentheses becomes optional. We will see
in a later chapter how we can use this feature to enhance our DSLs. Here is a simple
example that illustrates how it works:


class Message {
String message

def to( String person) {
println "$message, $person!"
}
}

def say (String message) {
new Message(message:message)
}

Here we have a simple Groovy class that has a to method. The say method returns
a Message object, so we can chain calls together. Using regular Java style syntax,
we can call:


say("Hello").to("Fred");

However, with Groovy's optional parentheses plus the option dot notation, we can
shorten this to:


say "Hello" to "Fred"

We can also invoke closures without the dot notation. We can modify the preceding
example so that the say method returns a map with closure entries as follows:


def say (String message) {
[ to: { person ->
println "$message, $person!"
}]
}

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