【问题标题】:Scala: why does a `for` comprehension on a Map sometimes yield a List?Scala:为什么地图上的“for”理解有时会产生一个列表?
【发布时间】:2013-06-29 15:39:38
【问题描述】:

为什么,在下面的代码示例中,isAListfor 理解生成一个列表,而其他两个生成映射?我想不出任何理由——唯一的区别似乎是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)
  }
}

输出

Map(2 -> unouno, 4 -> dosdos, 6 -> trestres)
Map(2 -> unouno, 4 -> dosdos, 6 -> trestres)
List((2,unouno), (4,dosdos), (6,trestres))

我对 Scala 比较陌生,如果我对某些事情过于天真,敬请见谅!

【问题讨论】:

  • 查看scalac -print的输出以查看脱糖程序。
  • @Paul:我刚才试过了,虽然输出看起来很有趣,但我不知道如何解释它......

标签: scala


【解决方案1】:

最近在 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

【讨论】:

  • 感谢您的及时答复!这个邮件列表的答案很有意义。
猜你喜欢
  • 2023-01-04
  • 2018-10-14
  • 1970-01-01
  • 2016-11-12
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多