3
votes

I've a Map where the key is a String and the value is an Int but represented as a String.

scala> val m = Map( "a" -> "1", "b" -> "2", "c" -> "3" ) 
m: scala.collection.immutable.Map[String,String] = Map(a -> 1, b -> 2, c -> 3)

Now I want to convert this into a Map[String, Int]

2

2 Answers

12
votes
scala> m.mapValues(_.toInt)
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)
6
votes

As shown in Brian's answer, mapValues is the best way to do this.

You can achieve the same effect using pattern matching, which would look like this:

m.map{ case (k, v) => (k, v.toInt)}

and is useful in other situations (e.g. if you want to change the key as well).

Remember that you are pattern matching against each entry in the Map, represented as a tuple2, not against the Map as a whole.

You also have to use curly braces {} around the case statement, to keep the compiler happy.