您好,欢迎来到宝玛科技网。
搜索
您的当前位置:首页为什么lambda表达式只能在SAM(函数式接口)中使用

为什么lambda表达式只能在SAM(函数式接口)中使用

来源:宝玛科技网

如下面的代码:

interface A {
    void f1();
    void f2(int x, int y);
}

A a1 = ()->xxx;
A a2 = (x, y)->xxx;
  • Important : The functional interface also known as Single Abstract Method Interface was introduced to facilitate Lambda functions. Since a lambda function can only provide the implementation for 1 method it is mandatory for the functional interface to have ONLY one abstract method.

  • Writing Lambda expression meaning we are implementing the interface that is functional interface. It should have one abstract method because at the time of lambda expression, we can provide only one implementation at once. So in the code snippet posted in the question, at any time we are giving only one implementation while declaring Lambda where we will have to implement for two abstract methods.

Matching Lambdas to Interfaces

A single method interface is also sometimes referred to as a functional interface. Matching a Java lambda expression against a functional interface is divided into these steps:

  • Does the interface have only one abstract (unimplemented) method?

  • Does the parameters of the lambda expression match the parameters of the single method?

  • Does the return type of the lambda expression match the return type of the single method?

If the answer is yes to these three questions, then the given lambda expression is matched successfully against the interface.

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baomayou.com 版权所有 赣ICP备2024042794号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务