Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 )
  }
like image 261
Faktor 10 Avatar asked Dec 29 '25 13:12

Faktor 10


1 Answers

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

kvpair.mapValues(_ * 2)

doubles each value in the map.

like image 131
elm Avatar answered Jan 01 '26 20:01

elm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!