Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 94 ]

The implicit doCall method


There is a third mechanism that you can use to invoke a Closure calling the
doCall() method of the closure itself:


public void run(Closure closure) {
closure.doCall()
}

The call and doCall methods might seem redundant, but there is an important
distinction. The call method is part of the groovy.lang.Closure class and can
accept any number of dynamic arguments. When we declare a closure in Groovy,
the doCall method is generated dynamically for each closure that we define in our
code, and has a signature that is specific to the individual closure.


The doCall method for the following closure will only accept a single string as its
parameter list:


def closure = { String s -> println s }

The general convention is to use either the unnamed () syntax or groovy.lang.
Closure.call() when invoking closures. The doCall method is used by the Groovy
runtime, and we should never directly invoke it ourselves. It is good to understand
its role however, if we ever want to write a closure in Java.


All closures we declare in our Groovy code will have a doCall method. However,
it's worth remembering that the groovy.lang.Closure class, which is a Java class,
is perfectly feasible for us to build a closure in Java:


public class MyClosure extends Closure{
public MyClosure(Object owner) {
super(owner);
}
public MyClosure(Object owner, Object thisObject) {
super(owner, thisObject);
}
Object doCall(String message) {
System.out.println(message);
return null;
}
}

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