3

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?

1 Answer 1

9

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)
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@user3858210 Yes, the part in the square brackets before the parentheses in the method definition lists names which you will use to refer to generic types in your method. The only generic type you are using is T, whereas Int is a concrete type, so there's no need to list it in the square brackets.
@David Frank Thank you. Earlier I wrote subMap[T, U], but I decided to change U to Int. This caused my error. But Scala Compiler named this error so indistinctly then I coudn't find it. Sorry for my poor english.
@user3858210 Please have a look at my update, it might be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.