【发布时间】:2021-04-03 22:43:33
【问题描述】:
假设我有一个方法将多个函数应用于一个值。
示例用法:
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);
是否可以使其应用具有各种输入和返回值的多个功能?
我尝试过使用通配符,但这不起作用。
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;
}
}
【问题讨论】:
-
使用
Stream或Optional。或者从他们的设计中汲取灵感。
标签: java generics functional-programming bounded-wildcard