Vikram
Vikram

Reputation: 333

Type mismatch, found Int required String

I'm having a strange issue. I'm trying to write a simple implicit class:

private implicit class CounterMap[A](map: Map[A, Int]) {
  def updateCounter(k: A): Map[A, Int] =
    map + (k → map.getOrElse(k, 0) + 1)
}

but when I try to compile, I get the following error:

error: type mismatch; found : Int(1) required: String map + (k → map.getOrElse(k, 0) + 1)

This post seemed similar Scala - type mismatch; found Int, required String, but it doesn't seem obvious to me that I've made the same mistake. I'm fairly new to using implicit classes and generics in Scala, so it's likely I'm missing something obvious here. Any help or explanation as to why I'm getting this error would be amazing.

Thanks in advance.

Upvotes: 3

Views: 2785

Answers (1)

justAbit
justAbit

Reputation: 4256

Problem seems to be with parenthesis. Enclose inner expression in parenthesis, as shown below:

map + (k -> (map.getOrElse(k, 0) + 1))

Other post that you mentioned had different problem. In that post, Int was used as type parameter, which is not the case here.

Upvotes: 3

Related Questions