【问题标题】:Functional Interface Implementations and use cases功能接口实现和用例
【发布时间】:2023-03-07 03:37:01
【问题描述】:

我只是想写一个功能接口来理解不同的用例。

看看我写的下面的代码,我知道我可以使用 lambda 表达式有不同的实现。除此之外,任何人都可以展示复杂的实现吗?

是否可以在 lambda 表达式中使用其他默认方法,即 addLikeOtherWay?如果是的话,在我的例子中如何?

为什么我的接口只有一种抽象方法?在我的界面中只有一个抽象方法的用例是什么?

public class Calculator {

    public static void main(String[] args) {
        ICalculator i = (int a, int b) -> a + b;
        System.out.println(i.add(5, 2));
        i = (int a, int b) -> a + b + a;
        System.out.println(i.add(5, 2));
    }
}

@FunctionalInterface
interface ICalculator {

    public int add(int a, int b);

    default int addLikeThis(int a, int b) {
        return a + b;
    }

    default int addLikeOtherWay(int a, int b) {
        return a + b + a + b;
    }

}

【问题讨论】:

  • 重复链接无法回答我的大部分问题
  • FunctionalInterface 的目标是允许您从中制作 lambda,因此它是抽象的,因为实现将是 lambda
  • 是否可以在 lambda 表达式中使用其他默认方法,即 addLikeOtherWay? 这里的 “在 lambda 表达式中” 到底是什么意思?我的意思是你可以调用i.addLikeOtherWay(5, 2)来确定调用该方法。
  • 为什么我的接口只有一个抽象方法?在我的界面中只有一个抽象方法的用例是什么? ...拥有functional interface is its representation as lambda 的用例之一,除此之外,您的界面可能不仅仅需要作为一个功能界面,这取决于您如何设计界面。

标签: java java-8 functional-programming functional-interface


【解决方案1】:

“是否可以在 lambda 表达式中使用默认方法?”是的。事实上,许多函数式接口都包含默认方法。您需要一个接口中的一个且只有一个抽象方法才能使其成为功能接口,否则 lambda 将不允许存在其他“未实现”的接口方法。但这里是如何应用默认值。下面的 BiFunction 接口是从 API 源中提取的,没有 JavaDoc。

以下代码有效,因为 BinaryOperatorUnaryOperator 分别扩展了 BiFunctionFunction

      BinaryOperator<Integer> add = (numb1,numb2)->numb1+numb2;
      UnaryOperator<Integer> mul = resultFromAdd->resultFromAdd*20;
      BinaryOperator<Integer> addThenMul = (numb1,numb2) ->add.andThen(mul).apply(numb1,numb2);
      int result = addThenMul.apply(10,20); // produces (10+20)*20 = 600

以下内容来自 Java API 源文件。

       @FunctionalInterface
       public interface BiFunction<T, U, R> {

          R apply(T t, U u);

          default <V> BiFunction<T, U, V> andThen(
                Function<? super R, ? extends V> after) {
             Objects.requireNonNull(after);
             return (T t, U u) -> after.apply(apply(t, u));
          }
       }

在上面的示例代码中,我可以使用BiFunction&lt;Integer,Integer,Integer&gt;Function&lt;Integer,Integer&gt;。但是*Operator 扩展假定所有 args 的类型相同,因此它们更易于使用(即更少的输入)。

【讨论】:

    【解决方案2】:

    为什么我的接口只有一种抽象方法?在我的界面中只有一个抽象方法的用例是什么?

    为了方便使用 lambda 表达式,它们是无名函数。 Lambda 表达式使代码富有表现力并减少混乱。它还使代码更具可读性。这是基于我使用 lambda 表达式的经验。

    【讨论】:

      猜你喜欢
      • 2010-12-18
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      • 2021-01-14
      相关资源
      最近更新 更多