我尝试了很多技巧,但我一直在努力。

(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)

以这种或那种方式。例如,这里有两个函数来重现问题。 sumInt工作正常...但总结错误。我不明白。

// 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)(_ + _)
有帮助吗?

解决方案

您需要将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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top