【问题标题】:Why function composing not available in IntFunction为什么函数组合在 IntFunction 中不可用
【发布时间】: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


【解决方案1】:

嗯,在您的示例中,使用 IntFunction&lt;Integer&gt; 并不是真正的最佳选择,这可能是您被卡住的原因。

当尝试处理接受 int 并返回 int 的函数时,您希望使用 IntUnaryOperator,它具有您正在寻找的 andThen(IntUnaryOperator) 方法。

它没有在IntFunction&lt;R&gt; 中实现的原因是你不能确定你的函数会返回下一个IntFunction&lt;R&gt; 所需的输入,当然是int

您的情况很简单,但想象一下使用 IntFunction&lt;List&lt;String&gt;&gt; 代替,您无法链接函数,因为 IntFunction&lt;R&gt; 不接受 List&lt;String&gt; 作为输入。


这是您更正的示例

IntUnaryOperator plusOne = x -> x + 1;
IntUnaryOperator square = x -> (int) Math.pow(x, 2);

IntUnaryOperator incrementThenSquare = plusOne.andThen(square);
int result = incrementThenSquare.applyAsInt(1);

System.out.println("result = " + result); // result = 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    相关资源
    最近更新 更多