【发布时间】:2021-04-04 13:47:22
【问题描述】:
我正在阅读第 3 章 Modern Java in action 中的函数组合部分。
我无法理解为什么我不能编写 IntFunctions。我犯了一个愚蠢的错误还是这背后有任何设计决策?
这是我在 cmets 中有错误的代码
package mja;
import java.util.function.Function;
import java.util.function.IntFunction;
public class AppTest2 {
public static void main(String[] args) {
IntFunction<Integer> plusOne = x -> x+1;
IntFunction<Integer> square = x -> (int) Math.pow(x,2);
// Compiler can't find method andThen in IntFunction and not allowing to compile
IntFunction<Integer> incrementThenSquare = plusOne.andThen(square);
int result = incrementThenSquare.apply(1);
Function<Integer, Integer> plusOne2 = x -> x + 1;
Function<Integer, Integer> square2 = x -> (int) Math.pow(x,2);
//Below works perfectly
Function<Integer, Integer> incrementThenSquare2 = plusOne2.andThen(square2);
int result2 = incrementThenSquare2.apply(1);
}
}
【问题讨论】:
-
您是从概念的角度提问吗?
IntFunction接口没有声明这样的方法,所以不能调用。 -
嗨@SotiriosDelimanolis,是的,我是从功能的角度问的。我不明白为什么不将这个方法添加到 IntFunction 中。
-
@GauthamM 它们是相关的,
Function也是一个功能接口,但其中有默认方法。所以这个问题是合法的
标签: java function lambda method-reference