operate(a b) java,Java 8 Lambda表达式-方法重载疑问

I'm trying to learn Lambda expressions,

interface MathOperartor has operate() overloaded for types int and float, I'm sure this should be possible to do using Lambda expressions, but can't quite seem to figure out what the issue is here:

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);

}

Please let me know what I'm doing wrong here and suggest a fix...

Update:

Ok, so I understood the concept of Functional Interface, My question was also about achieving what I was trying to do in the above code and I found couple of ways to do it.

Thank you every one for your valuable answers!

解决方案

A functional interface must is a 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.

your interface has declared 2 abstract methods that the lambda expression don't know where to going, and the lambda expression is an instance of that interface which means that must implements all the abstract methods declared in the interface. but you can adding default method to solve your problem in this case, for example:

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值