Durchführung von Vorgängen auf (insbesondere wie man eine Liste von) Long in Scala long
-
05-07-2019 - |
Frage
Ich habe eine Reihe von Techniken ausprobiert, aber ich stieß immer wieder auf
(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)
so oder so. Hier sind hier zwei Funktionen, um das Problem zu reproduzieren. Sumint funktioniert gut ... aber Sumlong -Fehler. Ich verstehe es nicht.
// 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)(_ + _)
Lösung
Sie müssen die 0 a machen Lang Konstante: "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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow