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 ...

Get Groovy for Domain-specific Languages - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.