Search code examples
scalacollectionsfor-comprehension

Scala function takes a map, modify the values and returns a map


I am trying to get my head around Scala for comprehensions as they relate to Maps. I have the following code and my intent is to break out the key-value pair, do something to the value and return the modified Map. Am I using the right function or should I use something else?

val kvpair = Map("a" -> 1, "b" -> 2, "c" -> 3)

def multiplyValues(map: Map[Char, Int]) = {

          for {
              char <- map._1  
              value <- map._2 * 2
          } yield (char, value )
  }

Solution

  • In Map, method mapValues conveys this requirement; for instance,

    kvpair.mapValues(_ * 2)
    

    doubles each value in the map.