Understanding Function Currying in Java

In the following tutorial, we will learn about function currying in Java.

What is a Function?

A function is a block of code written to simplify a task and to increase code reusability. A function can be used by calling it several times within the program, thus simplifying the task and improving the efficiency of the code. A function can accept no parameters or several parameters/arguments. Parameters/Arguments can be passed to functions as values to work with to compute what is required of the function.

For example, if we wanted to calculate the area of a circle we can just define a function to do so without writing the formula every time we need to perform the calculation. The function can just be called wherever the calculation of the area is required thus increasing the reusability and the efficiency of the code.

What is Function Currying in Java?

Function currying is the process of breaking down a multi-argument function to form multiple functions with single arguments such that the output is not altered.

Advantages of Function Currying

Function currying allows us to create more specialized functions and it also allows us to increase code reusability even further.

The following is a diagrammatic representation of Function Currying:

Function Currying in Java

Java Program on Function Currying

import java.util.function.Function;
public class FuncCurrying {

    public static void main(String[] args) {
        Function< Integer, Function<Integer,Integer> > multiply = x->y->x*y;
        System.out.println(multiply.apply(10).apply(10));
    }
    
}

Output:

100

The same program can also be implemented by currying three functions:

import java.util.function.Function;
public class FuncCurrying {

    public static void main(String[] args) {
        Function< Integer, Function<Integer, Function<Integer,Integer>>> multiply = x->y->z->x*y*z;
        System.out.println(multiply.apply(10).apply(10).apply(10));
    }
    
}

Output:

1000

Leave a Reply

Your email address will not be published. Required fields are marked *