-
Notifications
You must be signed in to change notification settings - Fork 0
Closures
Philip Ford edited this page May 28, 2017
·
30 revisions
Groovy closures are true closures, with access to the variables in the context in which they are defined. They are:
-
Contained in braces
-
They are functions.
-
Used in callbacks
-
The default parameter (if you do not provide parameters) is
it.[1,2,3].each { println it }
They can be used a lot like lambdas, passed as parameters to another function. (In other words, they are first-class objects.) But the Groovy documentation insists that they should not be thought of as lambdas.
{ <type> param1, <type> param2 ... ->
//Body
}- Again, parameters are optional.
- If no parameters are listed, the default parameter is
it. - Parameters, if present, are listed (comma-separated) immediately after the first brace, on the first line of the closure, and followed by a arrow.
- The code body begins on the next line.
- The output of the last line is the return value, with or without the
returnstatement.
Closures can be invoked like any other function:
closureName(<params...>)