Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this Groovy code?

Tags:

groovy

def foo(n) {
    return {n += it}
}
like image 822
Ant's Avatar asked Jul 18 '26 00:07

Ant's


1 Answers

The code defines a function/method foo that returns a closure. For the purpose of understanding this code, you can think of a closure as a method that has no name and is not attached to any object.

The closure can be invoked by passing it a single argument. The value returned by the closure will be n += it where it is the default name used to refer to a closure's argument. If you wanted the closure's argument to have a different name, e.g. closureParam you would need to define it explicity:

def foo(n) {
    return {closureParam -> n += closureParam}
}

The -> separates the closure's parameter list from the closure body. If no parameter list is defined, the default is a single parameter named it. Maybe an example of invoking the closure will help:

Closure closure = foo(2)
def closureReturnVal = closure.call(4) 
assert closureReturnVal == 6 // because 4 + 2 == 6

// you can omit .call when calling a closure, so the following also works
closure = foo(3)
assert 8 == closure(5) 
like image 194
Dónal Avatar answered Jul 21 '26 15:07

Dónal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!