Bhaskar Mishra Bhaskar Mishra - 1 year ago 133
Scala Question

Getting type Mismatch error with List of Maps

I have method which should except a string and List of Map.
I get an error on the second line as // get error as : type mismatch; found : List[scala.collection.immutable.Map[String,Any]] required: List[Map[String,org.json4s.JValue]] (which expands to) List[Map[String,org.json4s.JsonAST.JValue]:

val a = List(Map("inner/age" -> 35, "age" -> 27, "name" -> "foo"))
val r = jsonFieldUpdater(json, a)

If I do this

val r = jsonFieldUpdater(json, List(Map("inner/age" -> 35, "age" -> 27, "name" -> "foo")))

it works. How can I work in the first?

Answer Source

Scala type inference has inferred Map("a" -> 1, "b" -> "foo") as Map[String, Any] as Common super type of Int and String is Any

Guide the Scala compiler using explicit type annotation like this

val a: List[Map[String,org.json4s.JsonAST.JValue] =  List(Map("inner/age" -> 35, "age" -> 27, "name" -> "foo"))
val r = jsonFieldUpdater(json, a)

Note that this code will work in the proper context only because Ints and Strings are considered as org.json4s.JsonAST.JValue in the code

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download