gpt4 book ai didi

Java 8 Lambda 表达式——方法重载疑惑

转载 作者:行者123 更新时间:2023-12-02 07:41:19 25 4
gpt4 key购买 nike

我正在尝试学习 Lambda 表达式,

接口(interface)MathOperartor对int和float类型重载了operate(),我确信这应该可以使用Lambda表达式来完成,但似乎不太明白问题是什么这里:

public static void main(String[] args) {
LambdaLearning lb = new LambdaLearning();

MathOperartor add = (a , b )-> a + b; // error: The target type of this expression must be a functional interface
MathOperartor sub = (a , b) -> a - b; // same error
MathOperartor mul = (a , b) -> a * b; // ''
MathOperartor div = (a , b) -> a / b; // ''

System.out.println(lb.operate(10, 15, add));
System.out.println(lb.operate(10.5f, 15.5f, sub));
System.out.println(lb.operate(10, 15, mul));
System.out.println(lb.operate(10, 15, div));

}

interface MathOperartor{
public Object operate(int a, int b);
public Object operate(float a, float b);
}

private Object operate(int a, int b, MathOperartor math){
return math.operate(a,b);
}
private Object operate(float a, float b, MathOperartor math){
return math.operate(a,b);
}

请让我知道我在这里做错了什么并提出修复建议......

更新:

好的,所以我理解了函数式接口(interface)的概念,我的问题也是关于实现我在上面的代码中试图做的事情,我找到了几种方法来做到这一点。

感谢大家的宝贵回答!

最佳答案

一个functional interface必须是SAM接口(interface):

a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

你的接口(interface)声明了 2 个抽象方法,lambda 表达式不知道去哪里,而 lambda 表达式是该接口(interface)的一个实例,这意味着它必须实现 中声明的所有抽象方法界面。但您可以添加默认方法来解决这种情况下的问题,例如:

interface MathOperartor{
//it also can be removed, since a int can cast to a float automatically
default Object operate(int a, int b){
return operate((float)a, (float)b);
}
public Object operate(float a, float b);
}

关于Java 8 Lambda 表达式——方法重载疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44214496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com