是否有任何方法可以在 java 中表达 f 绑定(bind)类型,在调用站点返回通用响应?
interface Functor<T extends Functor<T>>
public <B> T<B> map(Function<A, B> fn); // won't compile because types don't match
如果类型永远不会改变,我可以使用 f 绑定(bind)类型,但对于映射,我需要一个新类型。有没有办法用java来表达这个?
我真正寻找的是任何可以获得更高种类的东西的方法,即使我知道 javac 不支持更高种类的类型。
假设我们有一个 List<A>
并希望此接口(interface)返回 List<B>
。但不希望这个界面知道任何关于 List
的信息.
最佳答案
阅读维基百科对仿函数的定义,听起来您想要定义一个能够从一个类别(Java 类型)映射到另一个类别的泛型类型。在上面的示例中,从 List<A>
进行映射至List<B>
其中类型 A
和B
是通用的。
如果这是您的目标,请考虑使用以下接口(interface)来定义 Functor
类型:
public interface Functor<CategoryA, CategoryB> {
public CategoryB map(CategoryA instance);
}
这声明 Functor
type 处理两种泛型参数类型,CategoryA
和CategoryB
并且对这些参数类型没有任何限制。它还声明了一个方法 map
必须实现从 CategoryA
类型的对象映射到 CategoryB
类型的对象.
假设,根据您的示例,您现在想要创建 Functor
的具体实例。映射自List<Integer>
至List<String>
。您可以创建以下类:
public class IntegerListToStringList implements Functor<List<Integer>, List<String>> {
@Override
public List<String> map(List<Integer> integerList) {
List<String> stringList = new ArrayList<>(integerList.size());
for(Integer intValue : integerList) {
stringList.add(Integer.toString(intValue));
}
return stringList;
}
}
然后您可以调用这个具体的 Functor
实现如下:
Functor<List<Integer>, List<String>> functor = new IntegerListToStringList();
Integer[] intArray = new Integer[] {2, 3, 5, 7, 11, 13};
List<Integer> intList = Arrays.asList(intArray);
List<String> stringList = functor.map(intList);
System.out.println("String list: " + stringList);
现在任何需要 Functor<List<Integer>, List<String>>
类型参数的方法可以接受 IntegerListToStringList
类型的实例.
关于带有泛型的 Java F 绑定(bind)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25440453/