I have the following Scala function:
def processMaps(toProcess : Map[Object,Object]) : Unit = {
// The 'toProcess' map might have a key named 'innerMap' which is itself a Map[String,String]
// Compiler Error: type mismatch; found : Object required: (String, String)
val innerMap : Map[String,String] = if (toProcess.containsKey("innerMap")) Map(toProcess.get("innerMap")) else null
// Do stuff to 'innerMap'...
}
The problem is that the innerMap
declaration produces the following compiler error:
type mismatch; found : Object required: (String, String)
Any idea why and what the fix is?
toProcess.get("innerMap")
returns an object, and you are trying to create a Map[String,String] from an object, that makes no senseyou could (but you shouldn't because it can throw exceptions in runtime) force a type cast with:
there are several details in your code that are not the best:
Map[Object,Object]
? you should make the key and values more type specific. Why do you have such a generic type? Are you mixing very different types? That's not idiomatic Scala. At least have a Map[String, Map]Map.get
method would return anOption
. You can do.getOrElse(defaultValue)
, or instead ofMap.get
do aMap.getOrElse(key, defaultValue)
null
s. Instead it usesOption
to encapsulate possible unexistent values, and then typical (monad) functions like.map
to apply some function/behaviour if the value is present