I have a map with the following structure:
Map[String, Map[String, String]]
Is there an elegant way of getting the value of the inner map?
Just do it the normal way... twice.
val m = Map("a" -> Map("b" -> "c"))
m("a")("b") // c
The first operation m("a") returns the inner Map[String,String]. The second operation that("b") returns the String inside of that returned Map.
It's the same as:
val m = Map("a" -> Map("b" -> "c"))
val m2 = m("a") // Map(b -> c)
m2("b") // c
On the other hand, if you think that they keys may not be there, then do this:
for {
x <- m.get("a") // x = Map(b -> c)
y <- x.get("b") // y = c
} yield y
// Some(c)
for {
x <- m.get("a") // x = Map(b -> c)
y <- x.get("d") // fails
} yield y
// None
for {
x <- m.get("c") // fails
y <- x.get("d") // doesn't run
} yield y
// None
For your example, key2 is an Option, just like m.get(key1), so you can handle it the same way:
val key1: String = "a"
val key2: Option[String] = Some("b")
for {
value1 <- m.get(key1)
k2 <- key2
value2 <- value1.get(k2)
} yield value2
// Some(c)
DerivedFeaturesLocations("outer_key").asInstanceOf[Map[String, String]]("inner_key"). Why is that?