Seq.reduce 哪些情况会使用 A 的超类型(B)作为参数?

Which situations would Seq.reduce take parameters with the supertype(B) of A?

API 方法减少:
def reduce[B >: A](op: (B, B) => B): B

val list = List(1,2,3)
list.reduce((i,j)=>(i+j))

i 和 j 肯定是 Int 类型,对吗?
哪些情况下 i 或 j 会是 A 的超类型(B)?

使用简单的数字类型并不能真正帮助说明这里的用例。

考虑:

class Vehicle(val wheels: Int)

object Vehicle {
  def combine(a: Vehicle, b: Vehicle) = new Vehicle(a.wheels + b.wheels)
}

class Car extends Vehicle(4)

class Bike extends Vehicle(2)

val list: List[Car] = List(new Car, new Car)

val gigaHorse: Vehicle = list.reduce(Vehicle.combine)

println(gigaHorse.wheels)

这里,显然 Vehicle.combine 是一种(相当晦涩的)方法,它以两个 Vehicle 为参数并从中产生一个“怪物”车辆。

因此,list 是一个汽车列表,但您可以使用 reduce 将它们缩减为单个车辆。


请注意,在您的情况下,您提供了一个 lambda 函数来减少并让编译器推断类型 B,这当然与列表中的项目类型完全相同。

但是 reduce 方法也允许您使用其他二进制函数,只要您能够将列表中的项目作为参数传递给该函数(这当参数类型是项目类型的超类型时恰好是这种情况。