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

在scala中对(特别是如何添加)long执行操作

  •  2
  • Trenton  · 技术社区  · 15 年前

    我试过很多技巧,但我总是碰到

    (fragment of wtf.scala):3: error: overloaded method value + with alternatives
    (Int)Int <and> (Char)Int <and> (Short)Int <and> (Byte)Int cannot be applied to (Long)
    

    以某种方式。例如,这里有两个函数来重现问题。萨姆特工作得很好…但是萨姆隆的错误。我不明白。

    // compiles (and works) fine
    def sumInt(list: List[Int]): Int = list.foldLeft(0)(_ + _)
    
    // compile time error. no + define on Long? I don't get it
    def sumLong(list: List[Long]): Long = list.foldLeft(0)(_ + _)
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Jim Ferrans    15 年前

    您需要使0成为 常数:“0L”:

    scala> def sumLong(list: List[Long]): Long = list.foldLeft(0L)(_ + _)
    sumLong: (List[Long])Long
    scala> scala> sumLong(List(1L, 2L, 3L))
    res2: Long = 6