Java 为什么函数组合在IntFunction中不可用
我正在阅读第三章《现代Java在行动》中的函数组合部分 我无法理解为什么我不能编写函数。我是否犯了愚蠢的错误,或者这背后是否有任何设计决策 这是我的代码,注释中有错误Java 为什么函数组合在IntFunction中不可用,java,function,lambda,method-reference,Java,Function,Lambda,Method Reference,我正在阅读第三章《现代Java在行动》中的函数组合部分 我无法理解为什么我不能编写函数。我是否犯了愚蠢的错误,或者这背后是否有任何设计决策 这是我的代码,注释中有错误 package mja; import java.util.function.Function; import java.util.function.IntFunction; public class AppTest2 { public static void main(String[] args) {
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);
}
}
mja包;
导入java.util.function.function;
导入java.util.function.IntFunction;
公共类AppTest2{
公共静态void main(字符串[]args){
IntFunction plusOne=x->x+1;
IntFunction square=x->(int)Math.pow(x,2);
//编译器在IntFunction中找不到方法和,不允许编译
IntFunction incrementThenSquare=加数第1和第1(平方);
int结果=递增的平方。应用(1);
函数plusOne2=x->x+1;
函数平方2=x->(int)数学功率(x,2);
//下面的工作非常完美
函数增量Thensquare2=加上2,然后(square2);
int result2=递增的平方2。应用(1);
}
}
在您的示例中,使用IntFunction
并不是一个真正的最佳选择,这可能就是您陷入困境的原因
当试图处理一个函数,该函数接受一个int
并返回一个int
,您需要使用IntUnaryOperator
,该函数具有您要查找的方法,然后使用(IntUnaryOperator)
它没有在IntFunction
中实现的原因是,您无法确定您的函数是否会返回下一个IntFunction
所需的输入,当然这是一个int
您的情况很简单,但是假设有一个IntFunction
,您不能链接函数,因为IntFunction
不接受列表作为输入
这是你改正的例子
IntUnaryOperator plusOne=x->x+1;
IntUnaryOperator square=x->(int)数学功率(x,2);
IntUnaryOperator递增THENSquare=加1和次(平方);
int结果=递增的平方。applyAsInt(1);
System.out.println(“result=“+result”);//结果=4
您是从概念的角度提问吗?IntFunction
接口没有声明这样的方法,所以您不能调用它。您好@SotiriosDelimanolis,是的,我是从函数的角度来问的。我不明白为什么不将此方法添加到IntFunction。@GauthamM它们是相关的,函数
也是一个函数接口,但其中有默认方法。。所以这个问题是合理的