Skip to content

Instantly share code, notes, and snippets.

@hyone
Created May 29, 2011 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyone/997560 to your computer and use it in GitHub Desktop.
Save hyone/997560 to your computer and use it in GitHub Desktop.
Accumulator by Java
interface Function1<A, R> {
R apply(A arg);
}
class Holder<T> {
public T value;
public Holder(T value) {
this.value = value;
}
}
public class ClosureTest {
static Function1<Integer, Integer> accumulator(int n) {
final Holder<Integer> holder = new Holder<Integer>(n);
return new Function1<Integer, Integer>() {
public Integer apply(Integer i) {
return holder.value += i;
}
};
}
public static void main(String[] args) {
Function1<Integer, Integer> acc = accumulator(0);
for (int i = 1; i <= 5; ++i)
System.out.println(acc.apply(i * 2));
}
}
// $ java ClosureTest
// 2
// 6
// 12
// 20
// 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment