Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 68 ]

Groovy methods look very similar to Java methods except that public visibility is the
default, so the public keyword can be left out. In addition, Groovy methods support
optional arguments, as do closures. As with dynamic variables, we need to use the
def keyword when defining a method that has a dynamic return type:


// Java method declaration
public String myMethod() {
...
}
// Groovy method declaration
String myMethod() {
...
}
// And with dynamic return type
def myMethod() {
}

Groovy script methods, which are declared in the same script, can be called directly
by name:


def greet(greeting) {
println greeting + ", World!"
}

greet ("Hello")
greet ("Goodbye")

The previous code gives the output:


Hello, World!


Goodbye, World!


Class methods are called by object reference, similar to Java:


class Greeting {
def greet(greeting) {
println greeting + ", World!"
}
}
greeting = new Greeting()
greeting.greet ("Hello")
greeting.greet ("Goodbye")

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