Skip to content

Instantly share code, notes, and snippets.

@davidandrzej
Created November 25, 2013 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidandrzej/7648308 to your computer and use it in GitHub Desktop.
Save davidandrzej/7648308 to your computer and use it in GitHub Desktop.
Unexpected (by me, at least) behavior of Scala `Map` when defined using `withDefaultValue`. Of course this is all documented in various places and probably makes sense to someone with a sophisticated understanding of the Scala Collections Library, but these are certainly potential "gotchas" in Map behavior. Credit: pointed out to me by Yuchen Zhao.
//
// CASE 1: Map without default value
// Result: behavior seems reasonable
//
val boo = Map("a" -> 1, "b" -> 2)
// boo: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2)
boo("c") // java.util.NoSuchElementException: key not found: c
boo.get("c") //res1: Option[Int] = None
//
// CASE 2: Map with default value
// Result: .get() can return None (!?)
//
val foo = Map("a" -> 1, "b" -> 2).withDefaultValue(0)
// foo: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2)
foo("c") // res2: Int = 0
foo.get("c") // res3: Option[Int] = None
//
// CASE 3: Map with default value, after applying .map()
// Result: default value "removed", weird type error
//
foo.map(identity)
// res4: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2)
foo.map(identity)("c")
// <console>:9: error: type mismatch;
// found : String("c")
// required: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Map[String,Int],(String, Int),?]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment