在 for 循环和条件语句中添加到 Scala 映射 [英] Adding to scala map within for loop and conditional statement
问题描述
我收到一条错误消息错误:类型参数 [Any] 不符合 trait Cloneable 的类型参数边界 [+A <: AnyRef]",我无法做出正面或反面.
I'm getting an error message of "error: type arguments [Any] do not conform to trait Cloneable's type parameter bounds [+A <: AnyRef]," which I can't make heads or tails of.
具体来说,
var M = mutable.Map[Int, mutable.Set[Int]]()
for(i <- 1 to 100; j <- 1 to 100) {
if(!M.contains(i)) {M += i -> mutable.Set[Int](j)}
else {M(i) += j}
}
(我实际上正在尝试更复杂的东西,但这是经过调整并简化到最低限度的错误生成代码)
(I'm actually trying something more complicated, but this is the error generating code tweaked and simplified to a minimum)
上面代码的最后一行生成了错误信息.如果我进一步剥离它
And the last line of the above code generates the error message. If I strip it down further
for(i <- 1 to 100; j <- 1 to 100) {
if(!M.contains(i)) {M += i -> mutable.Set[Int](j)}
}
它有效!
如何使上述代码工作?
推荐答案
Digal 诊断出问题(未能统一 if-else 分支的类型),看起来像是编译器错误.这是一个进一步简化的情况,在经过漫长的编译时间后,它会在 REPL 中出现错误,
Digal diagnosed the problem (failure to unify the types of the if-else branches) and it looks like a compiler bug. Here's a further simplified case that will give an error in the REPL, after a lengthy compilation time,
if (true) {
null: collection.mutable.Map[Int, Int]
} else {
null: collection.mutable.Set[Int]
}
与此同时,您可以使用在 if-else 语句中的某处散布的显式类型来编译代码,
In the meantime, you can get your code to compile with an explicit type sprinkled somewhere in the if-else statement,
for(i <- 1 to 100; j <- 1 to 100) {
if(!M.contains(i)) {M += i -> mutable.Set[Int](j)}
else {M(i) += j}: Unit
}
我在这里提交了一个问题:https://issues.scala-lang.org/浏览/SI-4938
I filed an issue here: https://issues.scala-lang.org/browse/SI-4938
这篇关于在 for 循环和条件语句中添加到 Scala 映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!