当我编写一些 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))
我想,它与 match-case-statement 的返回值有关。但我不是 Scala 专家,无法弄清楚此错误消息背后的原因以及我做错了什么。我希望,更聪明的人可以在这里提供帮助。
错误消息背后的原因是什么? match-case-statement 有什么问题?
更新:用 Scala 2.9.2 测试
最佳答案
您正在查看 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
}
}
关于scala - 编译 for 循环时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11916483/