Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scala Map.mapValues returns a (lazy) view. Hilarity ensues.
//
// TIL Scala Map.mapValues returns a lazy view
//
// This has the horrific consequence that supplying a non-pure function
// can yield a result map with unexpected / undesired behavior (see below)
//
// Further discussion here:
// http://stackoverflow.com/questions/14882642/scala-why-mapvalues-produces-a-view-and-is-there-any-stable-alternatives
// https://issues.scala-lang.org/browse/SI-4776
//
object TrickyMapValues extends App {
// Here comes trouble
var sideFX = 0.0
def nonPure(x: Double) = {
sideFX += 1.0
x + sideFX
}
val myMap = Map("a" -> 1.0, "b" -> 2.0)
val mapValues = myMap.mapValues(nonPure)
// If you think these should produce identical values,
// prepare to be delightfully surprised
println("sum1 = %.2f".format(mapValues.values.sum))
println("sum2 = %.2f".format(mapValues.values.sum))
println("sum3 = %.2f".format(mapValues.values.sum))
}
@josep2

This comment has been minimized.

Copy link

@josep2 josep2 commented Dec 3, 2016

Ran across your blog and tried this out. So tricky! I have never used mapValues but probably won't for sure now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment