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

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.