Immediately invoked function expressions are anonymous function blocks executed soon at the end of the block giving the return value. IIFEs are very common in JavaScript.
// IIFE in js
(function(arg) {
if (arg === 1)
return "one";
else
return "not one";
})(1);
In Groovy the same thing can be done using anonymous blocks which the language names as closure
. It is not the lexical closure that we are talking about, though it can be. The Closure
in Groovy is just a block of code.
Anyway we can have an IIFE in groovy using blocks and invoking it at the end of the block as shown below. Since the evaluated value is returned, we can omit the return statement.
// IIFE in Groovy
{arg ->
if (arg == 1)
"one"
else
"not one"
}(1)