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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With