I have Map[String, Any]
, for example from JSON deserializer:
def map: Map[String, Any] = Map("hello" -> Map("world" -> "value"))
And I want to get Option
of nested key "hello"."world"
:
val value = map.get("hello").flatMap {
case m: Map[String, String] => m.get("value")
case _ => None
}
assert(value == Some("value"))
But this solution is not type safe - it emits warning 'is unchecked since it is eliminated by erasure' and will fail on wrong value type.
How to accomplish this the safe way? Returning value if nested object is a map of valid/compatible type containing key "world"
or None
otherwise?
edit: This is not about Manifest[]
or TypeTag[]
. I know that exact Map type is not accessible in runtime but want better solution than casting keys somehow (is this safe btw?) and doing isinstanceof
for values.
flatMap
you already have anAny
not anOption[Any]
. But otherwise it's a valid question. I think the answer is you can't do this. – Daniel Darabosm.get
returnsOption[String]
so code is valid – Sergey AlaevTypeTag
s – Archegm.get
returnsOption[Any]
. But that's not the point.flatMap
let's you operate on the inside of theOption[Any]
. So you needcase m: Map[String, String]
and nocase None
. Just try it and you see. – Daniel DarabosMap[_,_]
, iterate over keys and check their type. I do not have any other ideas unfortunately – Archeg