Consider the following
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")
I would like to traverse the possible keys, and if the map contains one, traverse the map's values
The options I came up with are:
With a filter
for {
key <- possibleKeys
if (myMap contains key)
int <- myMap(key)
r <- 0 to int
} yield (r, int)
With getOrElse
for {
key <- possibleKeys
int <- myMap.getOrElse(key, Nil)
r <- 0 to int
} yield (r, int)
(Both return the same result:)
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))
Since I know Scala supports Options in for comprehensions, I was a bit surprised that this didn't work
for {
key <- possibleKeys
int <- myMap.get(key)
r <- 0 to int //<-- compilation error
} yield (r, int)
It complains about type mismatch; found : List[Int] required: Int
Which I vaguely understand why, but is there a way to make this work without the if
clause or the getOrElse
methods? (e.g. is there a way to get the myMap.get(key)
version to work?)