代码之家  ›  专栏  ›  技术社区  ›  hawkeye

为什么我不能在scala的整数序列上减少(+)。

  •  1
  • hawkeye  · 技术社区  · 6 年前

    我想得到 seq 属于 Integer 在斯卡拉。

    在我的头脑中,我想把一个加号折叠到整数上,如下所示:

    val seqOfIntegers:Seq[Int] = Seq(1, 2, 3, 4, 5)
    val sumOfIntegers = seqOfIntegers.reduce(+)
    

    这是无效的。

    相反,我必须这样做:

    val sumOfIntegers = seqOfIntegers.reduce(plus)
    ...
    def plus(a:Integer, b:Integer): Integer = { a + b}
    

    (我相信你可以把它说得很好——但我的观点是,原来的加号不能作为函数使用,错误消息也不能说明原因。)

    我的问题是: 为什么我不能在scala的整数序列上减少(+)。

    1 回复  |  直到 6 年前
        1
  •  6
  •   Andrey Tyukin    6 年前

    + Function2[Int, Int, Int] (Int, Int) => Int Int reduce (a: Int, b: Int) => a.+(b) (a: Int, b: Int) => a + b _ + _

    seq.reduce(_ + _)
    


    .reduce(+)

    object + extends ((Int, Int) => Int) { def apply(a: Int, b: Int): Int = a + b }
    Seq(1,2,3,4,5).reduce(+) 
    // res0: Int = 15
    

    def +(a: Int, b: Int) = a + b
    Seq(1,2,3,4,5).reduce(+)
    


    Seq(1, 2).reduce(+)
    

    推荐文章