Description:
This was my testing sample to understand how currying can be done in Java 8. I used both lambda and function reference to demonstrate currying behavior which would help great deal to understand behind the scene caricatures.
Code:
Explanation:
Functional reference implementation has to have (n-1) level function interface reference in the type declaration - IntFunction>. Here IntFunction is Java 8's feature where provided type is the type of the result of the function. Curried invocation of multiple's implementation has combination of apply and appyAsInt is used in curried fashion.
Resources:
- http://stackoverflow.com/questions/6134278/does-java-support-currying
- https://dzone.com/articles/whats-wrong-java-8-currying-vs
This was my testing sample to understand how currying can be done in Java 8. I used both lambda and function reference to demonstrate currying behavior which would help great deal to understand behind the scene caricatures.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import java.util.function.*; import static java.lang.System.out; public class CurryApplication { public static void main(String[] args) { IntBinaryOperator simpleAddWithLambda = (a, b) -> a + b; out.println("Simple Add (2params)= " + simpleAddWithLambda.applyAsInt(10, 20)); IntFunction<IntBinaryOperator> simpleMultipleWithFunctionalReference = new IntFunction<IntBinaryOperator>() { @Override public IntBinaryOperator apply(int value) { return new IntBinaryOperator() { @Override public int applyAsInt(int left, int right) { return value * left * right; } }; } }; out.println("Simple Multiple (3 params)= " + simpleMultipleWithFunctionalReference.apply(10).applyAsInt(20, 30)); IntFunction<IntUnaryOperator> curriedAdd = a -> b -> a + b; out.println("Curried Add (2 params)= " + curriedAdd.apply(4).applyAsInt(5)); IntFunction<IntFunction<IntUnaryOperator>> curriedMultiple = a -> b -> c -> c*a*b; out.println("Curried multiple (3 params)= "+curriedMultiple.apply(3).apply(4).applyAsInt(5)); } } |
Explanation:
Functional reference implementation has to have (n-1) level function interface reference in the type declaration - IntFunction
Resources:
- http://stackoverflow.com/questions/6134278/does-java-support-currying
- https://dzone.com/articles/whats-wrong-java-8-currying-vs