I would like to add code to a very nice explanation of @biziclop:
An example of currying in functional Java:
BiFunction<Integer, Integer, IntFunction<Integer>> currying = (x, y) -> z -> x * y / z; System.out.println(currying.apply(5, 6).apply(2)); // 15
As you can see, lambda is parameterized. In this example, we are trying to multiply 5 by 6, and then divide by 2.
The first apply(5) called and the variable x gets the value 5 , and the function becomes 5 * y / z
Then apply(6) invoked and the variable 'y' gets the value '6', and the function becomes 5 * 6 / z
Then apply(2) is called, and the variable 'z' gets the value '2', and the function becomes 5 * 6 / 2
As you can use currying, this method is little used in Java. Currying is useful in pure functional languages โโwhere functions are limited to a single argument and they benefit from currying, which converts a function that takes multiple arguments, so it can be called several times each with single arguments.
So how can you use currying in Java?
This is useful when you need to parameterize a function at several levels. For example, let's say we have several collections, each of which represents a different category, and we want to get certain elements from each category. The following is a simple example, given the two collections representing the recorded numbers, classified as ones and tens . Example:
public class Currying { private static List<String> ones = Arrays.asList("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"); private static List<String> tens = Arrays.asList("Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"); public static Function<String, Function<Integer, String>> getNumbers() { return units -> number -> { return units == "Ones" ? ones.get(number % 10) : tens.get(number % 10); }; } public static void main(String[] args) { Function<String, Function<Integer, String>> currying = getNumbers(); System.out.println(currying.apply("Tens").apply(8));
In the above example, the currying function returns another function currying.apply("Ones").apply(2)) ;
The first apply("Tens") , and the units variable becomes tens
Then apply(2) is called, and the variable number becomes 8 retrieving 80 from the tens collection.
The same logic applies to currying.apply("Ones").apply(2)) .