Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 98 ]

then: "we expect that Groovy won't find a matching Closure"
thrown MissingMethodException
when: "we pass too many parameters"
dynamicParams "String1", 1
then: "that should fail also"
thrown MissingMethodException
when: "passing a parameter to a Closure that does not expect one"
noParams "String"
then: "we expect that to fail"
thrown MissingMethodException

The preceding examples illustrate the use of dynamic versus static typing for closure
parameters. When we declare a closure with default parameters, then we can pass
pretty much whatever parameters we like to the closure, and Groovy will not mind.
When we declare a parameter but not its type, then Groovy will police the number
of parameters we try to pass but not their type. If we declare the type of a parameter,
then Groovy will check the parameters passed against that type. Finally, if we want
to enforce that a Closure does not accept a parameter, we can use the -> operator
with no parameter list.


Enforcing zero parameters


When we declare a closure with the default unnamed syntax, we will use the
it keyword in place of the assumed parameter. If we then invoke this closure
with no parameters, the closure gets called but a null is passed for the default
parameter value:


given: "a closure which declares no params"
def greet = { println "Hello, ${it}" }
when: "we invoke the closure"
greet()
then:
"Hello, null" == output()

Sometimes, we want to explicitly define a closure as having no parameters. Passing a
parameter to a closure like this will result in an exception being thrown:


given: "a closure which should take zero parameters"
def greet = { -> println "Hello,World!" }
when: "we try and call this with a parameter"
greet "Hello"
then: "we should get an exception"
thrown MissingMethodException

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