Scala:为什么地图上的“for"理解有时会产生一个列表? [英] Scala: why does a `for` comprehension on a Map sometimes yield a List?

查看:44
本文介绍了Scala:为什么地图上的“for"理解有时会产生一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在下面的代码示例中,isAListfor 推导式生成一个 List,而其他两个生成 Maps?我想不出任何原因——唯一的区别似乎是 isAList 的推导式声明了两个变量,而其他的则声明了一个或零.

Why, in the below code example, does isAList's for comprehension yield a List, but the other two yield Maps? I can't think of any reason - the only difference seems to be that there is isAList's comprehension declares two variables, and the others declare one or zero.

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 比较陌生,如果我对某些事情太天真了,请道歉!

I am comparatively new to Scala, so apologies if I'm being incredibly naive about something!

推荐答案

最近关于 ML 的讨论:

Recently discussed on the ML:

https://groups.google.com/forum/#!msg/scala-internals/Cmh0Co9xcMs/D-jr9ULOUISJ

https://issues.scala-lang.org/browse/SI-7515

建议的解决方法是使用元组来传播变量.

Suggested workaround is to use a tuple to propagate the variables.

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)

更多关于元组机制:

vals 的范围规则是什么在 Scala 中进行理解

这篇关于Scala:为什么地图上的“for"理解有时会产生一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆