Paul Graham, in his great article Revenge of the Nerds, claimed that languages vary in power. He mentioned a nice exercise - writing an accumulator generator:
We want to write a function that generates accumulators-- a function that takes a number n, and returns a function that takes another number i and returns n incremented by i.
Solution in Java is
public class Accumulator {
public interface Inttoint {
public int call(int i);
}
public static Inttoint foo(final int n) {
return new Inttoint() {
int s = n;
public int call(int i) {
s = s + i;
return s;
}};
}
public static void main(String... args) {
Inttoint accumulator = foo(1);
System.out.println(accumulator.call(2) == 3);
System.out.println(accumulator.call(3) == 6);
}
}
I am curious, whether in Java 8 (thanks to lambda) is already some elegant way how to write it similarly to Groovy, see below. I tried Function<Integer, Integer>
But I stuck with this compiler error.
local variables referenced from a lambda expression must be final or effectively final
So do you have some Java 8 solution?
Compare the old Java solution with the Groovy one
def foo(n) {
return {n += it}
}
def accumulator = foo(1)
assert accumulator(2) == 3
assert accumulator(3) == 6