Skip to content

Instantly share code, notes, and snippets.

@williamho
Created November 5, 2015 17:01
Show Gist options
  • Select an option

  • Save williamho/4b0ee44e259df572b16b to your computer and use it in GitHub Desktop.

Select an option

Save williamho/4b0ee44e259df572b16b to your computer and use it in GitHub Desktop.
mapValues doesn't map the values until the object is evaluated
// See https://issues.scala-lang.org/browse/SI-7005
scala> val m = Map(1 -> 2, 3 -> 4)
m: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)
scala> val m1 = m.mapValues { x => println("mapValues is being evaluated"); x + 2 }
mapValues is being evaluated
mapValues is being evaluated
m1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 4, 3 -> 6)
scala> m1.get(1)
mapValues is being evaluated
res16: Option[Int] = Some(4)
scala> m1.get(1)
mapValues is being evaluated
res17: Option[Int] = Some(4)
scala> val m2 = m1.map(identity)
mapValues is being evaluated
mapValues is being evaluated
m2: scala.collection.immutable.Map[Int,Int] = Map(1 -> 4, 3 -> 6)
scala> m2.get(1)
res18: Option[Int] = Some(4)
scala> m2.get(1)
res19: Option[Int] = Some(4)
@williamho

Copy link
Copy Markdown
Author

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