Search code examples
scala

Map both keys and values of a Scala Map


Scala's MapLike trait has a method

mapValues [C] (f: (B) ⇒ C): Map[A, C] 

But I sometimes want a different type:

mapKeysAndValues [C] (f: (A, B) ⇒ C): Map[A, C] 

Is there a simple way to do this which I am missing? Of course, this can be done with a fold.


Solution

  • map method iterates though all (key, value) pairs. You can use it like this:

    val m = Map("a" -> 1, "b" -> 2)
    
    val incM = m map {case (key, value) => (key, value + 1)}