Explain this Groovy code?
def foo(n) {
return {n开发者_JS百科 += it}
}
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)
I believe it's returning the double of the value you pass in, or a a concatenation of the same string twice if you give it a string.
精彩评论