Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 100 ]


  • A closure that accepts typed parameters will have a doCall method
    that accepts only the same specific types as the closure parameters to
    be generated:


def stringParams = { String something -> println something; }

class Closure3 extends groovy.lang.CLosure{
def doCall(String s) {
}
}

closure3 = new Closure3()

closure3.doCall("hello")
closure3.doCall(1) // exception

class Closure4 extends groovy.lang.Closure{
def doCall(int s) {
}
}

closure3 = new Closure3()

closure3.doCall("hello") // exception
closure3.doCall(1)

For this reason, closures are often best used with dynamically typed parameters, as it
is difficult to guard against the side effects. Consider the following code. We would
probably prefer it if the closure was applied to the whole of the list and not to only a
part of it. In this case, the each method will process all of the elements in the list up
until it encounters the string nine element, which causes an exception to be thrown:


given: "a hetrogeneous list"
def list = [1,3,5,7, "nine"]
and: "a typed closure"
def intParams = { int something -> println something; }
when: "we use the each method of the collection"
list.each intParams
then: "Fails when we hit list[4]"
thrown MissingMethodException

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