为什么在下面的代码示例中,isAList
的{{1}}理解会产生一个List,但另外两个会产生地图吗?我想不出任何理由 - 唯一的区别似乎是for
的理解声明了两个变量,其他变量声明了一个或零。
isAList
输出
object Weird {
def theMap: Map[Int, String] =
Map(1 -> "uno", 2 -> "dos", 3 -> "tres")
def main(args: Array[String]) {
val isAMap = for {
(key, value) <- theMap
} yield (key*2 -> value*2)
val isAlsoAMap = for {
(key, value) <- theMap
doubleKey = key*2
} yield (doubleKey -> value*2)
val isAList = for {
(key, value) <- theMap
doubleKey = key*2
doubleValue = value*2
} yield (doubleKey -> doubleValue)
println(isAMap)
println(isAlsoAMap)
println(isAList)
}
}
我对Scala比较陌生,如果我对某事感到非常天真,请道歉!
答案 0 :(得分:17)
最近在ML上讨论过:
https://groups.google.com/forum/#!msg/scala-internals/Cmh0Co9xcMs/D-jr9ULOUIsJ
https://issues.scala-lang.org/browse/SI-7515
建议的解决方法是使用元组来传播变量。
scala> for ((k,v) <- theMap; (dk,dv) = (k*2,v*2)) yield (dk,dv)
res8: scala.collection.immutable.Map[Int,String] = Map(2 -> unouno, 4 -> dosdos, 6 -> trestres)
关于元组机制的更多内容:
What are the scoping rules for vals in Scala for-comprehensions