javalambdajava-8currying

What does lambda with 2 arrows mean in Java 8?


I have read several Java 8 tutorials before.

Right now I encountered following topic: Does java support Currying?

Here, I see following code:

IntFunction<IntUnaryOperator> curriedAdd = a -> b -> a + b;
System.out.println(curriedAdd.apply(1).applyAsInt(12));

I understand that this example sum 2 elements but I cannot understand the construction:

a -> b -> a + b;

According to the left part of expression, this row should implement following function:

R apply(int value); 

Before this, I only met lambdas only with one arrow.


Solution

  • If you express this as non-shorthand lambda syntax or pre-lambda Java anonymous class syntax it is clearer what is happening...

    The original question. Why are two arrows? Simple, there are two functions being defined... The first function is a function-defining-function, the second is the result of that function, which also happens to be function. Each requires an -> operator to define it.

    Non-shorthand

    IntFunction<IntUnaryOperator> curriedAdd = (a) -> {
        return (b) -> {
            return a + b;
        };
    };
    

    Pre-Lambda before Java 8

    IntFunction<IntUnaryOperator> curriedAdd = new IntFunction<IntUnaryOperator>() {
        @Override
        public IntUnaryOperator apply(final int value) {
            IntUnaryOperator op = new IntUnaryOperator() {
                @Override
                public int applyAsInt(int operand) {
                    return operand + value;
                }
            };
            return op;
        }
    };