Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapView(<not computed>) in Scala

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?

like image 220
Dwi Setyo Aji Avatar asked Oct 30 '25 12:10

Dwi Setyo Aji


1 Answers

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.

like image 132
Tomer Shetah Avatar answered Nov 01 '25 02:11

Tomer Shetah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!