The scala doc document says:
a map map that maps each key this map to f(this(key)) . The resulting map wraps the original map without copying any elements.
So this was to be expected, but it really scares me, I will have to review a bunch of code tomorrow. I did not expect this behavior: - (
Just a workaround:
You can call toSeq to get a copy, and if you need to return it back to the toMap map, but these are unnecessary creation objects and have an idea about the effect on the use of map
It is relatively easy to write, a mapValues that does not create a view, I will do it tomorrow and post the code here if no one does it in front of me;)
EDIT:
I found an easy way to "force" the view, use ".map (identity)" after mapValues โโ(so there is no need to implement a specific function):
scala> val xs = Map("a" -> 1, "b" -> 2) xs: scala.collection.immutable.Map[java.lang.String,Int] = Map(a -> 1, b -> 2) scala> val ys = xs.mapValues(_ + Random.nextInt).map(identity) ys: scala.collection.immutable.Map[java.lang.String,Int] = Map(a -> 1315230132, b -> 1614948101) scala> ys res7: scala.collection.immutable.Map[java.lang.String,Int] = Map(a -> 1315230132, b -> 1614948101)
It's a shame that the return type is not really a view! otherwise it could be called "power" ...
Alois Cochard Feb 14 '13 at 19:53 2013-02-14 19:53
source share