I have a problem with type mismatch in Scala. Compiler returns an error:
error: type mismatch; found : Int required: String val v3:Int = (v1+v2)
This is code of my function:
def sumMaps[T, Int](m1: Map[T, Int], m2: Map[T, Int]): Map[T, Int] = {
val sameKeys = m1.keySet.intersect(m2.keySet)
var m3: Map[T, Int] = m1 ++ m2
for (key <- sameKeys) {
val v1:Int = m1(key)
val v2:Int = m2(key)
val v3:Int = (v1+v2)
//val v:Int = (m1(key) + m2(key))
m3 = m3 updated (key, v3)
}
m3
}
Why? Any idea what could be the problem?
You are redeclaring Int
as a type parameter when it is a concrete type.
You should change the method head to:
def sumMaps[T](m1: Map[T, Int], m2: Map[T, Int]): Map[T, Int] = {
When Int
is a type parameter, the compiler replaces (v1+v2)
with a string addition, so it becomes (v1.toString + v2.toString)
, this gave you the problem.
UPDATE
I came up with a simpler solution to your problem:
def sumMaps[T](m1: Map[T, Int], m2: Map[T, Int]): Map[T, Int] = {
(for (key <- m1.keySet ++ m2.keySet) yield {
val v1: Int = m1.getOrElse(key, 0)
val v2: Int = m2.getOrElse(key, 0)
key -> (v1 + v2)
}).toMap
}
Or an even simpler one:
def sumMaps[T](m1: Map[T, Int], m2: Map[T, Int]): Map[T, Int] = {
(m1 ++ m2).transform {
case (key, _) => m1.getOrElse(key, 0) + m2.getOrElse(key, 0)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.