Effectuer des opérations sur (en particulier comment ajouter une liste de) Long dans Scala

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

  •  05-07-2019
  •  | 
  •  

Question

J'ai essayé un certain nombre de techniques, mais je n'arrête pas de me heurter à

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

d'une manière ou d'une autre. A titre d'exemple, voici deux fonctions pour reproduire le problème. sumInt fonctionne très bien ... mais les erreurs sumLong. Je ne comprends pas.

// 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)(_ + _)
Était-ce utile?

La solution

Vous devez faire en sorte que le 0 soit une longue 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top