Performing operations (specifically how to add a list) Long in Scala

I have tried several methods, but I keep stumbling upon

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

      

anyway. As an example, there are two functions to reproduce the problem. sumInt works fine ... but sumLong errors. I do not understand.

// 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)(_ + _)

      

+2


source to share


1 answer


You need to create a constant 0 a Long : "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

      

+2


source







All Articles