Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Scala mapValues lazy?

When I call

System.err.println("Before")
System.err.flush()
val foo: Map[Int, T] = t mapValues (fn(_))
System.err.println(foo.head) //prevent optimiser from delaying the construction of 'foo' 
System.err.println("After")
System.err.flush()

with fn having a debug print statement inside, I get this output:

Before
...head item...
After
...debug print statement from fn...
...debug print statement from fn...

I don't understand why the debug print statements are being called after "After" is printed, and I don't understand why I'm getting it twice --- unless mapValues creates a lazy map?

like image 413
Mohan Avatar asked Sep 13 '16 15:09

Mohan


People also ask

What is Scala mapValues?

mapValues creates a Map with the same keys from this Map but transforming each key's value using the function f .

What does MAP values do in Scala?

Scala's Map is a collection of key-value pairs, where each key needs to be unique. Thanks to that, we have direct access to a value under a given key. Scala defines two kinds of maps, the immutable, which is used by default and mutable, which needs an import scala.


2 Answers

Yes it is. It maps to an intermediate class that holds fn and doesn't evaluate until access (again and again).

def mapValues[W](f: V => W): Map[K, W] = new MappedValues(f)

Use a strict map if you don't want lazy evaluation. That is:

collection map { case (k, v) => (k, fn(v)) }
like image 146
Michael Zajac Avatar answered Sep 19 '22 02:09

Michael Zajac


Keep in mind that the MappedValues implementation evaluates the function on every access -- different from a Scala lazy val that evaluates only once. You might be seeing the output twice when stepping through the code. Expanding the val foo in the debugger window will iterate over the values, calling function fn and generating debug output.

If you provide code for map t and function fn, then we might be able to help.

like image 27
Eric Bolinger Avatar answered Sep 21 '22 02:09

Eric Bolinger