0

考虑以下

val myMap: Map[String, List[Int]] = Map("a" -> List(1,2,3), 
                                        "b" -> List(4,5,6), 
                                        "d" -> List(7))

val possibleKeys: List[String] = List("c","a", "b", "e")

我想遍历可能的键,如果地图包含一个,则遍历地图的值

我想出的选项是:

带过滤器

 for {
    key <- possibleKeys
    if (myMap contains key)
    int <- myMap(key)
    r <- 0 to int
  } yield (r, int)    

getOrElse

  for {
    key <- possibleKeys
    int <- myMap.getOrElse(key, Nil)
    r <- 0 to int
  } yield (r, int)

(两者都返回相同的结果:)

List((0,1), (1,1), (0,2), (1,2), (2,2), (0,3), (1,3), (2,3), (3,3), (0,4), (1,4), (2,4), (3,4), (4,4), (0,5), (1,5), (2,5), (3,5), (4,5), (5,5), (0,6), (1,6), (2,6), (3,6), (4,6), (5,6), (6,6))

因为我知道 Scala 支持理解中的选项,所以我有点惊讶这不起作用

for {
    key <- possibleKeys
    int <- myMap.get(key)
    r <- 0 to int //<-- compilation error
  } yield (r, int)

它抱怨type mismatch; found : List[Int] required: Int

我隐约明白为什么,但是有没有办法在没有if条款或getOrElse方法的情况下完成这项工作?(例如,有没有办法让myMap.get(key)版本工作?)

4

2 回答 2

4

你试图在你的理解中混合不兼容的类型。您可以通过示例将选项转换为 Seq 来修复它。

for {
  key <- possibleKeys
  ints <- myMap.get(key).toSeq
  int <- ints
  r <- 0 to int
} yield (r, int)

在这个非常相似的问题中对这个问题有一个相当好的解释:Type Mismatch on Scala For Comprehension

于 2013-04-30T03:51:17.547 回答
0

您可以使用这些方法keySetapplyMap

for {
  key <- possibleKeys
  if myMap.keySet(key)
  int <- myMap(key)
  r <- 0 to int
} yield (r, int)

res5: List[(Int, Int)] = List((0,1), (1,1), (0,2), (1,2), (2,2), (0,3), (1,3), (2,3), (3,3), (0,4), (1,4), (2,4), (3,4), (4,4), (0,5), (1,5), (2,5), (3,5), (4,5), (5,5), (0,6), (1,6), (2,6), (3,6), (4,6), (5,6), (6,6))
于 2013-04-30T08:17:11.400 回答