Realización de operaciones en (específicamente cómo agregar una Lista de) en Scala

StackOverflow https://stackoverflow.com/questions/1605175

  •  05-07-2019
  •  | 
  •  

Pregunta

He intentado varias técnicas, pero sigo tropezando con

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

de una manera u otra. Como ejemplo, aquí hay dos funciones para reproducir el problema. sumInt funciona bien ... pero sumLong errores. No lo entiendo.

// 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)(_ + _)
¿Fue útil?

Solución

Debes hacer que el 0 sea Largo constante: " 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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top