2009-10-22 54 views
2

我已經嘗試了許多方法,但是我一直撞到進行動作(具體怎麼添加的列表)長在斯卡拉

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

回答

2

你需要做的0 恆: 「01」:

scala> def sumLong(list: List[Long]): Long = list.foldLeft(0L)(_ + _) 
sumLong: (List[Long])Long 
scala> scala> sumLong(List(1L, 2L, 3L)) 
res2: Long = 6 
+0

是的,就是這樣。謝謝。我正在努力理解錯誤。我是說「找到列表中的Int 0,然後將它添加到一個很長的?」但是,這是可以允許的,對嗎?我看到+(arg0:Long):在Int上定義長。 – Trenton 2009-10-22 07:57:55