wingoo220 2017-01-03 09:07 采纳率: 0%
浏览 794

scala reduceLeft 菜鸟求知

val at = Array((1, 1.29), (1, 1.62), (1, 1.73), (3, 3.35), (3, 3.27), (5, 5.81))

at.groupBy(_._1).foreach(i => {
print("key : " + i._1 + " value-sum : " + (i._2.reduceLeftDouble => x + item._2.toDouble)))
println
})

报错:
Error:(116, 68) type arguments [Double] do not conform to method reduceRight's type parameter bounds [B >: (Int, Double)]
print("key : " + i._1 + " value-sum : " + (i._2.reduceRightDouble => x + item._2.toDouble)))
^

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-05 13:17
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在Scala中,reduceRight方法的返回类型是Option[B],而不是B。因此,在调用reduceRight方法时,你需要提供一个Option[Double]类型的参数来匹配B

    你可以尝试以下修改:

    print("key : " + i._1 + " value-sum : " + (i._2.reduceRight(
        Option[Double](0)
    ))
    

    这将使用默认的Option[Double](0)作为B类型的参数,并将其传递给reduceRight方法。请注意,这可能不会按预期工作,因为reduceRight会忽略传入的值。如果你希望得到正确的结果,请确保你的数据集是有序的,或者使用sortBygroupByKey等操作。

    评论

报告相同问题?