MapView(<not computed>) in Scala

北城余情 提交于 2021-01-03 07:08:43

问题


I started learning Scala but I found a confusing problem about map. My code is like this:

val mymap = Map(1 -> "james",2 -> "justin")
println(mymap.view.mapValues(x => "hi" + x))
println(mymap.view.mapValues(x => x.toUpperCase))

but the result is

MapView(<not computed>)
MapView(<not computed>)

I am using view.mapValues because .map is deprecated. Any suggestion or doc I need to read about this?


回答1:


Try the following:

val mymap = Map(1 -> "james",2 -> "justin")
println(mymap.view.mapValues(x => "hi" + x).toMap)
println(mymap.view.mapValues(x => x.toUpperCase).toMap)

Note that in Scala 2.12 calling mapValues returned a Map. In Scala 2.13 mapValues was deprecated, with the message:

@deprecated("Use .view.mapValues(f). A future version will include a strict version of this method (for now, .view.mapValues(f).toMap).", "2.13.0")

In order to get a Map you should call .view.mapValues(f).toMap. If you don't call toMap, you get an instance of MapView, which is not materilized. For more information please read the great post: Stream vs Views vs Iterators.



来源:https://stackoverflow.com/questions/65289749/mapviewnot-computed-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!