Re: Write a function foo...
I also came up with
def foo(n){
{i-> n+=i}
}
...but I thought I'd explain the process a bit, just
to expose the magic of syntax sugar in groovy...
The Java example was
----
public static Inttoint foo(final int n) {
return new Inttoint() {
int s = n;
public int call(int i) {
s = s + i;
return s;
}
};
}
----
refactorings into groovy
i) This rather verbose code is returning an Inttoint object,
which has one method call(int i), this callback is a perfect
candidate for replacement with Closure as the return type.
ii) The intermediate instance variable s is not needed in
groovy as with true closures the variable n will be lexically
bound, so we can refer to n directly in the method body of call(int i){...
(Continue reading)