将各种类型的函数应用于值

Applying functions of various types to a value

假设我有一个方法将多个函数应用于一个值

用法示例:

String value = "a string with numb3r5";
Function<String, List<String>> fn1 = ...
Function<List<String>, String> fn2 = ...
Function<String, List<Integer>> fn3 = ...

InputConverter<String> converter = new InputConverter<>(value);
List<Integer> ints = converter.convertBy(fn1, fn2, fn3);

是否有可能使其应用具有各种输入和return值的多个函数?

我试过使用通配符,但这不起作用。

public class InputConverter<T> {
    private final T src;

    public InputConverter(T src) {
        this.src = src;
    }

    public <R> R convertBy(Function<?, ?>... functions) {
        R value = (R) src;

        for (Function<?, ?> function : functions)
            value = (R) function.apply(value);
                                       ^^^^^
        return value;
    }
}

您可以像下面这样在 Function 上使用链

Function<String, List<Integer>> functionChain = fn1.andThen(fn2).andThen(fn3);

您可以通过使用原始类型实现几乎相同的事情

@SuppressWarnings({"unchecked", "rawtypes"})
public <R> R convertBy(Function... functions) {
    Function functionsChain = Function.identity();

    for (Function function : functions) {
        functionsChain = functionsChain.andThen(function);
    }

    return (R) functionsChain.apply(src);
}

否则,我唯一看到的就是使用与 OptionalStream 相同的模式,就像评论中建议的那样

List<Integer> fileInputStreams = converter.convertBy(fn1)
        .convertBy(fn2)
        .convertBy(fn3)
        .get();

// with this implementation

public static class InputConverter<T> {
    private final T src;

    public InputConverter(T src) {
        this.src = src;
    }

    public <R> InputConverter<R> convertBy(Function<T, R> function) {
        return new InputConverter<>(function.apply(src));
    }

    public T get() {
        return src;
    }
}