Reputation: 63022
Here is a vanilla scala map:
scala> val m = Map( 'a'-> '1', 'b' -> 2)
m: scala.collection.immutable.Map[Char,AnyVal] = Map(a -> 1, b -> 2)
The Map iterator() method returns a tuple representing the (key,value). So if we want to see, say, just the values of the map we can do this:
scala> m.map( a => a._2)
res0: scala.collection.immutable.Iterable[AnyVal] = List(1, 2)
But how do we destructure the map entry ? The following does not work:
scala> m.map( (a,b) => b)
<console>:10: error: wrong number of parameters; expected = 1
m.map( (a,b) => b)
^
Upvotes: 5
Views: 2091
Reputation: 38045
You should use pattern matching:
m.map{ case (a, b) => b}
Map entry is just a Tuple2
.
Upvotes: 7
Reputation: 53348
Just in case you don't want to write the case {...}
syntax:
scala> import Function.{ tupled => $ }
import Function.{tupled=>$}
scala> Map(1 -> "a") map $((a,b) => b)
res1: scala.collection.immutable.Iterable[String] = List(a)
scala> Map(1 -> "a") map $((a,b) => a -> s"$b!")
res2: scala.collection.immutable.Map[Int,String] = Map(1 -> a!)
Upvotes: 4