Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass lambda expression with arguments as parameters in Java 8?

Here is what I tried. and it does not even compile.

public class LambdaExample {

    public static Integer handleOperation(Integer x, Integer y,  Function converter){
                return converter.apply(x,y);
    }

    public static void main(String[] args){
         handleOperation(10,10, Operation::add);
    }

}

class Operation {

    public int add(Integer x, Integer y){
        return x+y;
    }

}

Couple of things I am trying to acheive/learn here is:

1) how to pass lambda expression as method parameter ( in main method above)

2) how to pass parameters to the function (in handleOpertion method, there is compilation error that apply takes only one parameter)

like image 477
brain storm Avatar asked Dec 15 '22 14:12

brain storm


1 Answers

A Function takes an input x and yield a result y. Thus you are not looking for a Function (not mentioning that you used a raw type) when doing return converter.apply(x,y);, but for a BiFunction<Integer, Integer, Integer> or more simpler, a BinaryOperator<Integer> since every type parameter is identical.

1) how to pass lambda expression as method parameter ( in main method above)

By providing a lambda expression that respect the contract of the BinaryOperator<Integer> interface, i.e a method that takes two Integer as parameter and return an Integer.

handleOperation(10,10, (a, b) -> a + b)

2) how to pass parameters to the function (in handleOpertion method, there is compilation error that apply takes only one parameter)

Because a function is of the form f => u thus the apply method takes a single argument and yield a single result, like a mathematical function such as f(x) = 2 * x (refer to the first part of the answer).

Here is what I tried. and it does not even compile.

To make your code compile, you can either make the method static or create a new instance before using the method reference. Then it will refer to the add method of the new instance when handleOperation will call the apply method of the function.

handleOperation(10,10, new Operation()::add);

Note that this method already exists in the JDK, it's Integer::sum. It takes two primitive int values instead of Integer references but it's close enough so that the auto-boxing mechanism will make this method valid to appear as a BinaryOperator<Integer> in the method context.

like image 194
Alexis C. Avatar answered Jan 13 '23 15:01

Alexis C.