【问题标题】:Why does the type parameter of reduceLeft contain a lower bound?为什么 reduceLeft 的类型参数包含下界?
【发布时间】:2012-01-11 23:31:39
【问题描述】:

reduceLeft在一些Seq[A]上的签名是

def reduceLeft [B >: A] (f: (B, A) => B): B 

A 的类型是已知的,但下限>: 告诉我们B 可以是A 的任何超类型。

为什么会这样?为什么不

def reduceLeft (f: (A, A) => A): A

我们已经知道序列的头部是类型A,所以我想不出B 怎么可能不等于A。你能举个例子,B 是某种超类型吗?

【问题讨论】:

    标签: scala scala-collections reduce type-parameter


    【解决方案1】:

    假设你的 B 类有一个方法combine(other:B): B。现在您在As 的列表中调用reduceLeft((b,a) => b.combine(a))。由于combine 的返回类型为BreduceLeft 的类型参数需要为B

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 1970-01-01
      • 2021-07-29
      • 2011-05-18
      • 2019-06-07
      相关资源
      最近更新 更多