Created
May 29, 2011 08:13
-
-
Save hyone/997560 to your computer and use it in GitHub Desktop.
Accumulator by Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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