【问题标题】:Java F-Bound types with generics具有泛型的 Java F-Bound 类型
【发布时间】:2014-08-22 05:57:51
【问题描述】:

有什么方法可以在调用站点返回通用响应的 java 中表达 f 绑定类型?

interface Functor<T extends Functor<T>>
  public <B> T<B> map(Function<A, B> fn); // won't compile because types don't match

如果类型从不改变,我可以使用 f-bound 类型,但在 map 的情况下,我需要一个新类型。有没有办法用java来表达?

即使我知道 javac 不支持更高种类的类型,我真正在寻找的是任何可以获得类似更高种类的东西的方法。

假设我们有一个List&lt;A&gt;,并希望这个接口返回一个List&lt;B&gt;。但是不想让这个接口知道List的任何信息。

【问题讨论】:

  • interface Functor&lt;T extends Functor&lt;T&gt;, A, B&gt; ?
  • 那不会让我在地图中返回T&lt;B&gt;。我当前的类型是 T,我需要返回一个 T
  • 那么A 是从哪里来的?它没有在任何地方正式定义。
  • 这就是我想要弄清楚的。也许我正在从更高阶类型的角度来看待这个问题,更新了我的评论以更好地反映这一点。
  • 您能添加一个您正在考虑的用法示例吗?你会用什么调用 Functor.map,你希望返回什么?

标签: java generics functor bounded-wildcard


【解决方案1】:

阅读 Wikipedia 对 functor 的定义,听起来您想定义一个能够从一个类别(Java 类型)映射到另一个类别的泛型类型。在上面的示例中,从List&lt;A&gt; 映射到List&lt;B&gt;,其中AB 类型是通用的。

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

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

这声明Functor 类型处理两种通用参数类型,CategoryACategoryB,并且对这些参数类型没有任何约束。它还声明必须实现一个方法map,该方法从CategoryA 类型的对象映射到CategoryB 类型的对象。

假设,根据您的示例,您现在要创建一个从 List&lt;Integer&gt; 映射到 List&lt;String&gt;Functor 的具体实例。您可以创建以下类:

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&lt;List&lt;Integer&gt;, List&lt;String&gt;&gt; 类型参数的方法都可以接受IntegerListToStringList 类型的实例。

【讨论】:

  • 如果我将ListFunctor&lt;A, B&gt; 类参数化,那应该可以找到。更高种类的部分是将其范围缩小,以便输入和输出具有相同的外部类型(本示例中的列表),但可以通过使所有基本实现都提供它来降低此要求...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多