Using `map` function on Map in Scala
Solution 1
In this case, mapValues does seem the more appropriate method to use. You would use the map method when you need to perform a transformation that requires knowledge of the keys (eg. converting a product reference into a product name, say).
That said, the map method is more general as it gives you acces to both the keys and values for you to act upon, and you could emulate the mapValues method by simply transforming the values and passing the keys through untouched - and that is where you are going wrong in your code above. To use the map method correctly, you should be producing a (key, value) pair from your function, not just a key:
val discGizmos2=gizmos.map{ case (k,v) => (k,v*0.9) } // pass the key through unchanged
Solution 2
It can be also:
val discGizmos2 = gizmos.map(kv => (kv._1, kv._2*0.9))
Related videos on Youtube
Arun Manivannan
Updated on June 06, 2022Comments
-
Arun Manivannan almost 2 years
First off, apologies for the lame question. I am reading the `Scala for the Impatient' religiously and trying to solve all the exercise questions (and doing some minimal exploration)
Background : The exercise question goes like - Setup a map of prices for a number of gizmos that you covet. Then produce a second map with the same keys and the prices at a 10% discount.
Unfortunately, at this point, most parts of the scaladoc are still cryptic to me but I understand that the map function of the
Map
takes a function and returns another map after applying a function (I guess?) -def map[B](f: (A) ⇒ B): HashMap[B]
. I tried googling but couldnt get much useful results formap function for Map in scala
:-)My Question: As attempted in my variation 3, does using
map
function for this purpose make any sense or should I stick with the variation 2 which actually solves my problem.Code :
val gizmos:Map[String,Double]=Map("Samsung Galaxy S4 Zoom"-> 1000, "Mac Pro"-> 6000.10, "Google Glass"->2000) //1. Normal for/yield val discountedGizmos=(for ((k,v)<-gizmos) yield (k, v*0.9)) //Works fine //2. Variation using mapValues val discGizmos1=gizmos.mapValues(_*0.9) //Works fine //3. Variation using only map function val discGizmos2=gizmos.map((_,v) =>v*0.9) //ERROR : Wrong number of parameters: expected 1
-
Arun Manivannan over 10 yearsNice. I love the way Scala allows you to do the same thing in more ways than one. Thanks !!
-
Daenyth almost 10 yearsIt's worth noting that
mapValues
creates a view on the existing map whereasmap
creates an entire new map. -
piyushGoyal over 9 yearsthis is equivalent of using a tuple.. i.e. kv is simply a tuple.
-
Saskia over 4 years
map
doesn't need to return a tuple. At least anymore. The result is an Iterable then. -
Lucas Lima over 4 yearsWhy is there a
case
keyword there?