scala - type mismatch compiler error when concatenating two maps using getOrElse -
i'm trying concatenate mutable immutable map in scala.
case class result(val key: string, val number: int) object test extends app { val map1 = scala.collection.mutable.map[string, list[result]]() val map2: map[string, list[result]] = map("test" -> list(new result("0", 0))) map1 ++= map2.map(c => (c -> (c._2 + map1.getorelse(c._1, list[result]())))) } but compiler says:
type mismatch; found : list[result] required: string when change listresult "test" compiler says:
type mismatch; found : java.io.serializable required: string i'm quite confused. use getorelse wrong way?
regards cyrill
map1 ++= map2.map(c => (c -> (c._2 + map1.getorelse(c._1, list[result]())))) map on map gets passed each element of map. c (string, list[result]). this
(c -> (c._2 + map1.getorelse(c._1, list[result]())) is ((string, list[result), (list[result]). wrong. imagine meant
(c._1 -> (c._2 + map1.getorelse(c._1, list[result]())) but still has type mismatch. think you're hitting common problem of implicit any2string +, , compiler wants string shouldn't.
anyway,
(c._1 -> (c._2 ++ map1.getorelse(c._1, list[result]())) seems work
map1 ++= map2.map(c => (c._1 -> (c._2 ++ map1.getorelse(c._1, list[result]())))) also, nil bit neater:
map1 ++= map2.map(c => (c._1 -> (c._2 ++ map1.getorelse(c._1, nil)))) and clearer again (imo) comprehension
for ((k,v) <-map2) map1 += (k-> (v ++ map1.getorelse(k, nil)))
Comments
Post a Comment