这是我尝试过的。它甚至不编译。
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;
}
}
我在这里尝试实现/学习的几件事是:
1) 如何将
lambda expression
作为方法参数传递(在上面的 main
方法中)2)如何给函数传递参数(在
handleOpertion
方法中,存在compilation
错误,apply只带一个参数)
最佳答案
您的 handleOperation
方法采用一个实现 Function
的对象, Operation::add
(方法引用)不符合条件。此外,对于两个参数,您需要改用 BiFunction
。
这是一个应该有效的示例:
public class LambdaExample {
public static Integer handleOperation(Integer x, Integer y, BiFunction<Integer, Integer, Integer> converter){
return converter.apply(x,y);
}
public static void main(String[] args){
handleOperation( 10,10, new Operation() ); // should return 20
}
}
class Operation implements BiFunction<Integer, Integer, Integer> {
public Integer apply(Integer x, Integer y){
return x+y;
}
}
更新:
public class LambdaExample {
public static Integer handleOperation(Integer x, Integer y, BiFunction<Integer, Integer, Integer> converter){
return converter.apply(x,y);
}
public static void main(String[] args){
handleOperation( 10,10, Operation::add ); // should return 20
}
}
class Operation {
public static int add(Integer x, Integer y){
return x+y;
}
}
关于lambda - 如何在 Java 8 中传递带有参数的 lambda 表达式作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494261/