16

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 for map 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

2 Answers 2

23

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
Sign up to request clarification or add additional context in comments.

3 Comments

It's worth noting that mapValues creates a view on the existing map whereas map creates an entire new map.
map doesn't need to return a tuple. At least anymore. The result is an Iterable then.
Why is there a case keyword there?
9

It can be also:

val discGizmos2 = gizmos.map(kv => (kv._1, kv._2*0.9))

2 Comments

Nice. I love the way Scala allows you to do the same thing in more ways than one. Thanks !!
this is equivalent of using a tuple.. i.e. kv is simply a tuple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.