Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 5

[ 97 ]

Closure parameters


In our previous examples, we have made use of the it keyword. When a closure
accepts only a single parameter, we are able to refer to this parameter as it and are
free from having to explicitly define the parameter. The possible syntax definitions
for a closure are:



  • The default case allows any parameters to be passed to the closure:
    {
    // statements
    }

  • The closure does not accept any parameters:
    { ->
    // statements
    }

  • The closure can accept one to many parameters with optional type annotations:


{ [type] param (,[type] param)* ->
// statements
}

The parameter list is a comma-separated list of parameter names with optional type
definitions. Closures behave slightly different depending on whether we supply the
optional type:


given: "Closures with various parameter definition"
def defaultParams = { println it; }
def dynamicParams = { something -> println something; }
def intParams = { int something -> println something; }
def stringParams = { String something -> println something; }
def noParams = { -> }
when: "Invoking these with valid parameters"
defaultParams 1
defaultParams "String"
dynamicParams 1
dynamicParams "String"
intParams 1
stringParams "String"
noParams ()
then: "we expect them to work"
notThrown MissingMethodException
when: "we pass an incorrect type for a typed parameter"
stringParams 1
Free download pdf