RubyのinjectみたいなメソッドをJavaでどう書く
こうかな。苦しいな。誰か教えてくださり。
総称型を使えばもうちょいそれらしく(?)なるんかも。
import static org.junit.Assert.assertEquals; import org.junit.Test; public class Inject { interface Proc { int execute(final int n, final int m); } public int inject(int[] input, int init, Proc proc) { int result = init; for (int i : input) { result = proc.execute(result, i); } return result; } @Test public void testInject() throws Exception { assertEquals( 55, inject(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, new Proc() { @Override public int execute(int n, int m) { return n + m; } })); assertEquals( 3628800, inject(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 1, new Proc() { @Override public int execute(int n, int m) { return n * m; } })); } }
オフラインどう書くの懇親会で、「Javaには関数オブジェクトがないじゃないですかー」って言われたけど、たしかに上記はコレジャナイ感がすごい。