5

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)
                       ^
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560

2 Answers2

7

You should use pattern matching:

m.map{ case (a, b) =>  b}

Map entry is just a Tuple2.

senia
  • 37,745
  • 4
  • 88
  • 129
  • ur probably on the right track but there is a syntax error: console>:1: error: illegal start of simple expression – WestCoastProjects Dec 14 '13 at 20:20
  • 1
    Need different brackets. `m.map{ case (a, b) => b}` – Kigyo Dec 14 '13 at 20:22
  • 1
    @kigyo BTW why does this need brace instead of parens? – WestCoastProjects Dec 14 '13 at 20:25
  • @javadba: see [this answer](http://stackoverflow.com/questions/18048664/confusing-scala-higher-order-function-call-syntax/18051129#18051129). It should be a `BlockExpr` to create a `PartialFunction`. – senia Dec 14 '13 at 20:29
  • @javadba because it's a partial function. It is only defined on elements that can be matched to (a,b). Since all elements in a map have the structure (a,b) it is defined for all elements in the map. – Kigyo Dec 14 '13 at 20:29
  • 2
    btw, this is not a `PartialFunction`, just an anonymous pattern match – kiritsuku Dec 14 '13 at 21:22
  • @sschaef: Thank you! I was sure that `PartialFunction` is created here. – senia Dec 15 '13 at 03:51
  • @sschaef Would you either describe or point to a doc explaining how "anonymous pattern match" and PartialFunction are related? thx – WestCoastProjects Dec 15 '13 at 18:44
  • @javadba They stand in relation in so far that you have to use pattern matching to match the input a `PartialFunction` takes, that's why a lot of people assume that the occurrence of `{ case ... }` is a `PartialFunction`. – kiritsuku Dec 15 '13 at 20:06
4

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!)
kiritsuku
  • 52,967
  • 18
  • 114
  • 136