4

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?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
  • 1
    Add `toMap` at the end. Also, read the [**docs**](https://www.scala-lang.org/api/current/scala/collection/View.html) and check the [**faq**](https://docs.scala-lang.org/tutorials/FAQ/index.html#what-is-the-difference-between-view-stream-and-iterator). – Luis Miguel Mejía Suárez Dec 14 '20 at 13:35
  • I already try adding toMap but got and error of `value toMap is not a member of Unit` thats why I ask to SO – Dwi Setyo Aji Dec 14 '20 at 13:37
  • You are adding `toMap` to the `println` probably... which obviously won't work. – Luis Miguel Mejía Suárez Dec 14 '20 at 13:38
  • I even try use this `val test: MapView[Int, String] = mymap.view.mapValues(x => "hi" + x)` and `println(test)` but still the result is not computed – Dwi Setyo Aji Dec 14 '20 at 13:48

1 Answers1

6

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.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35