Scala中的MapView(<未计算>) [英] MapView(<not computed>) in Scala
问题描述
我开始学习Scala,但发现有关 map
的一个令人困惑的问题.我的代码是这样的:
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))
但结果是
MapView(<not computed>)
MapView(<not computed>)
我正在使用 view.mapValues
,因为不推荐使用 .map
.我需要阅读任何建议或文档吗?
I am using view.mapValues
because .map
is deprecated. Any suggestion or doc I need to read about this?
推荐答案
尝试以下操作:
val mymap = Map(1 -> "james",2 -> "justin")
println(mymap.view.mapValues(x => "hi" + x).toMap)
println(mymap.view.mapValues(x => x.toUpperCase).toMap)
请注意,在Scala 2.12中,调用 mapValues
已弃用,并显示以下消息:
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")
为了获取 Map
,您应该调用 .view.mapValues(f).toMap
.如果不调用 toMap
,则会得到 Stream vs Views vs Iterators .
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.
这篇关于Scala中的MapView(<未计算>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!