Reputation: 1091
"map map to map", what a mouthful.
Anyway, I can do:
val list = List(1, 2, 3)
val list2 = list map (item => item + 1)
println(list2)
// List(2, 3, 4)
Why does the following not work?:
val ages = Map("alice" -> 21, "bob" -> 22)
val ages2 = ages map ((name, age) => (name, age + 1))
, and how do I go about making it work?
EDIT: I figured out that I had to do:
val ages2 = ages map {case (name, age) => (name, age + 1)}
, but that doesn't answer my first question, which is why my naive first approach does not work.
Upvotes: 2
Views: 498
Reputation: 149538
It doesn't work because the Scala compiler doesn't automatically decompose the Tuple2
(which is the type of the key value pairs) in your Map
.
This would work:
val ages2 = ages.map(pair => (pair._1, pair._2 + 1))
As it uses the tuple argument as a whole.
As you've noticed, using partial function syntax also works and allows you to automatically decompose the tuple:
val ages2 = ages map { case (name, age) => (name, age + 1) }
This is currently a limitation of the compiler. With dotty (the new new Scala compiler), this will be provided out of the box.
Upvotes: 5