Chapter 4
[ 55 ]
If we have multiple statements on a line, a semicolon is required. The semicolon can
still be left off the last statement in the line:
class Account {
def id; double balance; Customer owner
}
Optional parentheses
The parentheses around method call parameters are optional for top-level
statements. We have been looking at this language feature since the start of the
chapter. Our Hello World program is:
println "Hello, World!"
This is, in fact, a call to the built-in Groovy println method and can be expressed
with parentheses if we want, as follows:
println ("Hello, World!")
Similarly, the call to the Account.credit method in our Account example could
have been written with parentheses:
savings.credit( 20.00 )
When a method call or closure call takes no arguments, then we need to supply
the parentheses. The compiler will interpret any reference to a method without
parameters as a property lookup for the same name. A reference to a closure will
return the closure itself:
getHello = { return "Hello, World" }
// Prints the closure reference
hello = getHello
println hello
// Parens required because
// println
// on its own is a reference to a property called println
println ()
// calls the closure
hello = getHello()
println hello