أداء العمليات على (وتحديدا كيفية إضافة قائمة) طويلة في Scala

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

  •  05-07-2019
  •  | 
  •  

سؤال

لقد جربت عددًا من التقنيات ، لكني أستمر في الاصطدام

(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 يعمل بشكل جيد ... ولكن أخطاء sumlong. انا لم احصل عليها.

// 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