为什么我不能组合两个具有相同参数类型的不同函数?

Why can't I compose two different functions with identical parameter types?

我有以下代码:

        Function<String,Integer> f1=s->Integer.valueOf(s)+1;
        Function<String,Integer> f2=s->Integer.valueOf(s)*2;
        Function<String,Integer> f3=f1.compose(f2);

这是我收到的错误:

method compose in interface Function<T,R> cannot be applied to given types;

这段代码有什么问题?

然后我查看了文档中的compose()

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
    Objects.requireNonNull(before);
    return (V v) -> apply(before.apply(v));
    }

我无法完全理解它。哪位,给我解释一下,可以组合的函数的参数之间的关系?

组合两个函数意味着一个函数的结果将作为另一个函数的输入。因此,如果您有两个函数,它们具有彼此相同的输入类型和相同的输出类型,但输入和输出类型不同,则它们不能以任何顺序组合。

在您的特定情况下,您请求的组合函数将 f1() 应用于 f2() 的结果,但 f2() 的结果是 Integer,而 f1() 需要 String 类型的输入。解决该问题的一种方法是修改 f1() 使其在 Integers:

上运行
        Function<Integer, Integer> f1 = i -> i + 1;
        Function<String, Integer> f2 = s -> Integer.valueOf(s) * 2;
        Function<String, Integer> f3 = f1.compose(f2);

如果您无法修改 f1(),那么您可以将中间转换插入到 String 到您的合成链中:

        Function<String, Integer> f1=s->Integer.valueOf(s)+1;
        Function<String, Integer> f2 = s -> Integer.valueOf(s) * 2;
        Function<String, Integer> f3 = f1.compose(f2.andThen(Integer::toString));

但是,当然,所有这些来回转换到 String 都是昂贵的。

函数组成'chains'个函数,函数本身有一个结果类型。当然,具有不同输入类型和输出类型的函数不能 'reused' 在同一函数中。看 compose 按顺序做函数: 第一步:f2 中的字符串,输出为整数。然而,f1 中 f2 的输出具有作为输入的字符串,而不是整数。因此,您的功能 compose 将不起作用。如果第一个函数的输出可以用作第二个函数的输入,则只能链接一个函数:

        Function<Integer, Integer> f1 = i -> i + 1;
        Function<String, Integer> f2 = s -> Integer.valueOf(s) * 2;
        Function<String, Integer> f3 = f1.compose(f2);