Explain this Groovy code? -
def foo(n) { return {n += it} }
the code defines function/method foo
returns closure. purpose of understanding code, can think of closure method has no name , not attached object.
the closure can invoked passing single argument. value returned closure n += it
it
default name used refer closure's argument. if wanted closure's argument have different name, e.g. closureparam
need define explicity:
def foo(n) { return {closureparam -> n += closureparam} }
the ->
separates closure's parameter list closure body. if no parameter list defined, default single parameter named it
. maybe example of invoking closure help:
closure closure = foo(2) def closurereturnval = closure.call(4) assert closurereturnval == 6 // because 4 + 2 == 6 // can omit .call when calling closure, following works closure = foo(3) assert 8 == closure(5)
Comments
Post a Comment