开发者

Scala 2.8 and Map views

开发者 https://www.devze.com 2023-01-07 20:38 出处:网络
In 2.7 I could do the following: 开发者_Python百科val lazyM: Map[_, _] = map.projection.mapElements(v => expCalc(v)) //MAP VIEW

In 2.7 I could do the following:

开发者_Python百科val lazyM: Map[_, _] = map.projection.mapElements(v => expCalc(v)) //MAP VIEW

I can't find a way of doing this in 2.8 and actually ending up with a map:

val m: Map[_, _] = map.view.map(kv => kv._1 -> expCalc(kv._2)).toMap //STRICT

This seems like a significant loss of functionality and therefore I assume it's hiding in the collection library somewhere. Anyone have any ideas?

Edit - stupidly I assumed that mapValues was exactly the same as the old mapElements


Somewhat surprisingly, Map#mapValues produces a (transformed) view:

scala> Map(1 -> 2, 3 -> 4, 5 -> 6)
res0: scala.collection.immutable.Map[Int,Int] = Map((1,2), (3,4), (5,6))

scala> res0.mapValues { v => println("computing from " + v); v + 1 }
computing from 2
computing from 4
computing from 6
res1: scala.collection.immutable.Map[Int,Int] = Map((1,3), (3,5), (5,7))

scala> res1(1)
computing from 2
res2: Int = 3

scala> res1(5)
computing from 6
res3: Int = 7
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号