考虑以下
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)
版本工作?)