在编写一些 Scala 代码时,我在尝试编译代码时收到了一条奇怪的错误消息。我将代码分解为更简单的代码(从语义的角度来看这根本没有意义,但仍然显示错误)。
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))
我想,这与匹配案例语句的返回值有关。但我不是 Scala 专家,无法弄清楚此错误消息背后的原因以及我做错了什么。我希望,更聪明的人可以在这里提供帮助。
错误消息背后的原因是什么?match-case-statement 有什么问题?
更新:使用 Scala 2.9.2 测试