带有泛型的 Java F 绑定(bind)类型

标签 java generics functor bounded-wildcard

是否有任何方法可以在 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>其中类型 AB是通用的。

如果这是您的目标,请考虑使用以下接口(interface)来定义 Functor类型:

public interface Functor<CategoryA, CategoryB> {
    public CategoryB map(CategoryA instance);
}

这声明 Functor type 处理两种泛型参数类型,CategoryACategoryB并且对这些参数类型没有任何限制。它还声明了一个方法 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/

相关文章:

c++ - 调用 Operator() "function call"返回对数组元素的引用

c++ - 重载时 friend 的替代>>?

STL - 如何对 std::map 进行排序?

java - 具有从 Hibernate 调用的 OUT 参数的 Oracle 存储过程

java - OSGi kf 框架的引导类路径扩展支持

.net - 插入到通用字典中可能存在重复键吗?

java - 如何修复Java中的 "type argument S is not within bounds of type-variable E"

java - 我是 Maven 新手,有更好的方法来搜索原型(prototype)吗?

java - NAO Robotics学生在AMD 64位平台上编译错误: Can't load IA 32-bit . dll

javascript - 有没有办法在 typescript 中实例化通用文字类型?