【发布时间】:2018-01-16 13:54:33
【问题描述】:
我正在尝试在java中使用某种模式匹配,所以我想出了这个方法:
public Function<SimpleEntry<T, R>[], R> matchWith(T match){
return functions -> Stream.of(functions)
.filter(entry -> entry.getKey().equals(match))
.findFirst()
.map(Entry::getValue)
.orElse(null);
}
这显然行不通,我找不到相关的问题。
想法是使用这样的方法:
final String value = matchWith(Type.B).apply(
new SimpleEntry<>(Type.A, "Type A matches"),
new SimpleEntry<>(Type.B, "Type B matches")
)
注意:我可能需要像 Function<Pair<T, R>..., R> 这样声明返回类型才能拥有它..我也不知道该怎么做。
那么如何为一个返回泛型函数的方法声明泛型呢?
【问题讨论】:
-
泛型和数组不能混用,因为数组在运行时有不同的类型,但泛型类型只有在编译时才知道。请改用列表或集合。
标签: java generics functional-programming pattern-matching