2

If I have this code in Scala below:

val prices = Map("bread" -> 4.56, "eggs" -> 2.98, "butter" -> 4.35)
prices.map((k,v) => (k, v-1.1)).toMap

I get the error:

The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, `{ case (k, v) =>  ... }`

But when I change the second line to:

prices.map{ case(k,v) => (k, v - 1.1) }.toMap

The above error goes away? Can someone please explain when would I need to use case in the map function?

LP45
  • 303
  • 3
  • 14

1 Answers1

2

As mentioned in @chrisaycock's comment, there is no auto-untupling in a regular map. You need to use it like this:

scala> val prices = Map("bread" -> 4.56, "eggs" -> 2.98, "butter" -> 4.35)
prices: scala.collection.immutable.Map[String,Double] = Map(bread -> 4.56, eggs -> 2.98, butter -> 4.35)

scala> prices.map(kv => (kv._1, kv._2-1.1)).toMap
res0: scala.collection.immutable.Map[String,Double] = Map(bread -> 3.4599999999999995, eggs -> 1.88, butter -> 3.2499999999999996)
evan.oman
  • 5,922
  • 22
  • 43
  • Oh that never came to my head... Thank you for pointing that out! Also in the map function if I use a case is it just the syntax that I have to use the {}. And I can't do something like this: `prices.map( case(k,v) => (k, v - 1.1) ).toMap` I know like `()` is used for parameters and `{}` is used for a function body. So is the `case` keyword a function? – LP45 Jun 16 '16 at 21:55
  • I do not think `case` would be considered a function. I do know that `l.map(/*do stuff*/)` is equivalent to `l.map{/*do stuff*/}` – evan.oman Jun 16 '16 at 22:07
  • Sorry for the late reply. Oh they are interchangeable when you do not have case? – LP45 Jun 16 '16 at 23:35
  • This is a complicated topic, [this answer](http://stackoverflow.com/a/4387118/2661491) provides a pretty good overview for the most common cases. – evan.oman Jun 16 '16 at 23:53