简体   繁体   English

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

[英]Applying functions of various types to a value

Let's say I have a method that applies multiple functions to a value .假设我有一个将多个函数应用于 value的方法。

Example usage:示例用法:

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);

Is it possible to make it apply multiple functions with various inputs and return values ?是否可以使其应用具有各种输入和返回值的多个功能?

I've tried using wildcards, but this doesn't work.我试过使用通配符,但这不起作用。

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;
    }
}

You can use a chain on Function like the following您可以在Function上使用链,如下所示

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

You can achieve nearly the same thing by using raw types您可以通过使用原始类型来实现几乎相同的目标

@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);
}

Otherwise, the only other I see is to use the same pattern as Optional or Stream like suggested in the comments否则,我看到的唯一其他方法是使用与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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM