Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 102 ]

In the preceding code, we implemented a simple closure, which accepts a single
string parameter. We can now make use of this closure within our Groovy code,
as follows:


given: "an instance of a Java Closure"
def stringParams = new StringClosure(this)
when: "Invoking this with the parameters defined by the doCall"
stringParams "String"
then: "we expect them to work"
notThrown Exception
when: "we pass an incorrect type for the doCall parameter"
stringParams 1
then: "we expect that Groovy won't find a matching Closure"
thrown MissingMethodException

Now, we can try a more complex closure that accepts multiple different parameter
types by implementing multiple doCall methods in the closure:


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

We can then pass the different parameter types to this closure, and it will work fine:


given: "an instance of a Java Closure"
def multiParams = new MultiClosure(this)
when: "Invoking these with the parameters defined by the doCall"
multiParams "String"
then: "we expect them to work"
notThrown Exception
when: "Invoking these with the parameters defined by the doCall"
multiParams 1
then: "we expect them to work"
notThrown Exception

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