我只是想编写一个功能接口来理解不同的用例。
通过查看下面编写的代码,我了解可以使用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;
}
}
答案 0 :(得分:1)
“是否可以在lambda表达式中使用默认方法?”是。实际上,许多功能接口都包含默认方法。您只需在接口中使用一个且仅一个抽象方法即可使其成为功能接口,否则,lambda会“禁止”使用其他接口方法,这是不允许的。但是这里是如何应用默认值的方法。下面的BiFunction
接口是从API来源中提取的,没有JavaDoc。
以下代码之所以有效,是因为BinaryOperator
和UnaryOperator
分别扩展了BiFunction
和Function
。
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<Integer,Integer,Integer>
和Function<Integer,Integer>
。但是*Operator
扩展名对所有args都假定使用相同的类型,因此它们更易于使用(即减少键入)。
答案 1 :(得分:0)
为什么我只能使用一种抽象方法进行接口?在我的界面中只有一个抽象方法的用例是什么?
为了方便使用lambda表达式,它们是无名函数。 Lambda表达式使代码更具表现力,并减少混乱。它还使代码更具可读性。这是基于我使用lambda表达式的经验。