Closure return values
Closure declarations syntax provides no means of defining a return value. Every closure does, however, return a value with each invocation. A closure can have explicit return
statements. If a return
statement is encountered, then the value defined in the return
statement is returned; otherwise, execution continues until the last statement in the closure block:
given: "a closure that returns values" def closure = { param -> if (param == 1) return 1 2 } expect: closure(1) == 1 // return statement reached closure(-1) == 2 // ending statement evaluates to 2
If no return
statement is encountered, then the value returned by the closure is the result of evaluating the last statement encountered in the closure block. If the last statement has no value, the closure will return null
:
void voidMethod() { } given: "a closure returning void method" def nullReturn = { voidMethod() } expect: nullReturn() == null