Java 'reduceLeft' 签名/下界类型参数

Java 'reduceLeft' signature / Lower-bounded Type Arguments

以下签名有效且在 Scala 中常用:

trait Collection[A] {
    def reduceLeft [B >: A] (f: (B, A) => B): B
}

然而,由于 >: 是 Java 中 super 的 Scala 等效项,我的第一个想法是转换此签名(将函数类型替换为 BiFunction 并使使用 Use-Site variance annotations aka Bounded Wildcards) 将是

interface Collection<A> {
    <B super A> B reduceLeft(BiFunction<? super B, ? super A, ? extends B> mapper)
}

但是哦不!编译器抱怨 <B super A> 中的 super 标记,因为你不能有下界类型变量!现在,我如何在 Java 代码中编写此方法,而不必回到 Java 世界中不存在泛型的时候?


是的,我知道你认为我可以使用 B extends A,但这不是一回事,如我的实现所示:

public <R extends E> R reduceLeft(BiFunction<? super R, ? super E, ? extends R> mapper)
{
    if (this.isEmpty())
    {
        return null;
    }

    Iterator<E> iterator = this.iterator();
    R first = iterator.next(); // doesn't work, but would if R was a super-type of E (R super E)
    while (iterator.hasNext())
    {
        mapper.apply(first, iterator.next());
    }

    return first;
}

相反,我不得不使用这个稍微更受限制的版本:

public E reduceLeft(BiFunction<? super E, ? super E, ? extends E> mapper)
{
    if (this.isEmpty())
    {
        return null;
    }

    Iterator<E> iterator = this.iterator();
    E first = iterator.next();
    while (iterator.hasNext())
    {
        first = mapper.apply(first, iterator.next());
    }

    return first;
}

Scala 方法定义中的 B >: A 约束是必要的,因为:

  1. Scala 使用声明站点变量,不可变集合在它们包含的元素类型上是协变的
  2. reduceLeft 在概念上需要 return 类型 A 的值,但是使用 A 作为 return 类型意味着在协变中使用它位置,与已经声明的方差冲突,即 A 必须是协变的。

解决这种差异冲突的技巧是引入 B 泛型。

现在,正如您所提到的,Java 采用了使用点变化,因此任何用 Java 编写的集合都将是不变的。这也意味着使用 A 作为方法的 return 类型没有问题,即在逆变位置。所以,下面的定义应该足够了——不需要 B 类型:

interface Collection<A> {
  A reduceLeft(BiFunction<? super A, ? super A, ? extends A> reducer);
}

然而,如您所见,A 曾经是下限然后是上限的净效应是 A 基本上是不变的——不可能从通配符中获益不使用向下转换的边界。这意味着我们可以简化签名(这与 Stream.reduce 非常相似):

interface Collection<A> {
  A reduceLeft(BiFunction<A, A, A> reducer);
}

此外,类型 BiFunction<A, A, A> 已经存在于 Java 8 中,名称为 BinaryOperator<A>

你不能; Java 认为此功能不够有用。现在 Java 正在更多地使用高阶函数,也许这会改变。

我将通过接受 "witnesses" A <: B:

的函数来模拟此功能
interface Collection<A> {
  static class Witness {
    static <B, A extends B> Function<A, B> witness() {
    return new Function<A, B> {
      public B apply(A value) {
        return value;
      }
    };
  }
  //Could take a custom type instead of Function if we want to enforce
  //that arbitrary functions aren't passed.
  //Could also just use foldLeft rather than reduceLeft
  <B> B reduceLeft(BinaryOperator<B, B, B> mapper, Function<A, B> witness);
}

Collection<Double> collectionOfDoubles = ...
BinaryOperator<Number, Number, Number> numberFunction = ...
//I haven't tested whether we need to pass explicit type arguments
collectionOfDoubles.reduceLeft(numberFunction, Collection.Witness.witness());

但我们从这里开始走上 greensupunning 之路。

请注意,方差中有实际值;与例如@Ionut 的解决方案,collectionOfDoubles.reduceLeft 调用是不可能的,因为 DoubleNumber 不是同一类型。

一个简单的解决方案是诉诸 static 方法。然后您可以同时声明 Collection 的元素类型和缩减的 return 类型,从而轻松地声明 E extends R 与它的关系:

public static <R, E extends R> R reduceLeft(
    Collection<? extends E> c, BiFunction<? super R, ? super E, ? extends R> mapper) {
    if(c.isEmpty()) return null;
    Iterator<? extends E> iterator = c.iterator();
    R value = iterator.next();
    while(iterator.hasNext()) value=mapper.apply(value, iterator.next());
    return value;
}

这种方法的一个直接优势是它适用于 所有 集合,而不仅仅是声明方法的类型。

请注意,如果您为函数请求适当的标识值,也可以完全删除元素类型和结果类型之间的关系,Stream API 也支持这一点。这也修复了您为空集合实现 returning null 的缺陷:

public static <R, E> R reduceLeft(Collection<? extends E> c,
                      R identity, BiFunction<? super R, ? super E, ? extends R> mapper) {
    if(c.isEmpty()) return identity;
    R value=identity;
    for(E e: c) value=mapper.apply(value, e);
    return value;
}

现在不需要声明 ER 之间的关系,这个版本也可以是您的集合类型的实例方法:

public <R> R reduceLeft(R identity, BiFunction<? super R, ? super E, ? extends R> mapper) {
    if(isEmpty()) return identity;
    R value=identity;
    for(E e: this) value=mapper.apply(value, e);
    return value;
}

但是如果你不喜欢提供标识值的要求,你也可以提供一个函数用于第一个元素的初始转换,这对于 R 是一个超级的情况来说是微不足道的- E 的类型:

public <R> R reduceLeft(Function<? super E, ? extends R> cast,
                        BiFunction<? super R, ? super E, ? extends R> mapper) {
    if(isEmpty()) return null;
    Iterator<E> it=iterator();
    R value=cast.apply(it.next());
    while(it.hasNext()) value=mapper.apply(value, it.next());
    return value;
}

所以如果 RE 的超类型,传递 t->tFunction.identity() 作为 cast 参数就足够了。但它也允许更多 RE 之间不存在关系的用例。