Alex Rivera | Logout

why both transform and map methods in scala?

Asked 2013-05-24T14:18:54.463
8

I'm having trouble understanding the difference between / reason for, for example, immutable.Map.transform and immutable.Map.map. It looks like transform won't change the key, but that just seems like a trivial variation of the map method. Am I missing something?

I was expecting to find a method that applied a function to the (key,value) of the map when/if that element was accessed (rather than having to iterate through the map eagerly with the map function). Does such a method exist?

Edit
Report

1 Answer

4

You can do exactly that with mapValues. Here is the explanation from the docs:

def mapValues[C](f: (B) ⇒ C): Map[A, C]

Transforms this map by applying a function to every retrieved value.

f - the function used to transform values of this map.

returns - a map view which maps every key of this map to f(this(key)). The resulting map wraps the original map without copying any elements.

edit:

Although extending classes of the collection API is not often a good idea, it could work like this:

class LazilyModifiedMap[A,B,C](underlying: Map[A,B])(f: (A,B) => C) extends Map[A,C] {
  def get(key: A) = underlying.get(key).map( x => f(key, x))

  def iterator = underlying.iterator.map { case (k,v) => (k, f(k,v)) }

  def -(key: A) = iterator.toMap - key

  def +[C1 >: C](kv: (A,C1)) = iterator.toMap + kv
}
answered 2013-05-24T14:22:17.203

Your Answer