2012-08-11 117 views
6

當我編寫一些Scala代碼時,在嘗試編譯代碼時遇到了一個奇怪的錯誤消息。我把代碼分解成了一個更簡單的代碼(從語義的角度來看,這完全沒有意義,但仍然顯示錯誤)。編譯for循環時出現奇怪的錯誤

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

import scala.collection.mutable.ListBuffer 

val map = scala.collection.mutable.Map[Int, ListBuffer[Int]]() 
for (i <- 1 to 2) { 
    map.get(0) match { 
    case None => map += (1 -> ListBuffer[Int](1)) 
    case Some(l: ListBuffer[Int]) => l += i 
    } 
} 

// Exiting paste mode, now interpreting. 

<console>:12: error: type arguments [Any] do not conform to trait Cloneable's t 
pe parameter bounds [+A <: AnyRef] 
       for (i <- 1 to 2) { 
         ^

當for循環的末尾添加一個額外的行,代碼工作:

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

import scala.collection.mutable.ListBuffer 

val map = scala.collection.mutable.Map[Int, ListBuffer[Int]]() 
for (i <- 1 to 2) { 
    map.get(0) match { 
    case None => map += (1 -> ListBuffer[Int](1)) 
    case Some(l: ListBuffer[Int]) => l += i 
    } 
    1 // <- With this line it works 
} 

// Exiting paste mode, now interpreting. 

warning: there were 1 unchecked warnings; re-run with -unchecked for details 
import scala.collection.mutable.ListBuffer 
map: scala.collection.mutable.Map[Int,scala.collection.mutable.ListBuffer[Int]] 
= Map(1 -> ListBuffer(1)) 

我想,它有事情做與比賽-case語句的返回值。但是我不是Scala專家,無法弄清楚這個錯誤信息背後的原因以及我做錯了什麼。我希望有更聰明的人可以幫忙。

錯誤信息背後的原因是什麼?匹配情況聲明有什麼問題?

更新:使用Scala 2.9.2

+0

這可能是一個錯誤。隨着2.10它工作正常。 – sschaef 2012-08-11 18:41:38

回答

6

你在行動中看到this bug測試。它固定在2.10,並且在this answer中有一個簡單的解決方法 - 只需在某處添加類型註釋:

for (i <- 1 to 2) { 
    map.get(0) match { 
    case None => map += (1 -> ListBuffer[Int](1)) 
    case Some(l: ListBuffer[Int]) => (l += i): Unit 
    } 
} 
+0

非常感謝您指出這一點。 – 2012-08-11 19:48:15