Skip to content

Instantly share code, notes, and snippets.

@cespare
Created November 16, 2011 00:03
Show Gist options
  • Save cespare/1368825 to your computer and use it in GitHub Desktop.
Save cespare/1368825 to your computer and use it in GitHub Desktop.
scala default map updating
import scala.collection.mutable.Map
import scala.collection.mutable.Buffer
val foo = Map[Int, Buffer[Int]]() withDefault ((key) => Buffer())
foo(1) = Buffer(1, 2)
foo(1) += 3
foo(1) // => ArrayBuffer(1, 2, 3)
/* This all seems as expected */
foo(2) // => ArrayBuffer()
foo(2) += 3
foo(2) // => ArrayBuffer()
/* This is a little annoying, but it makes sense when you think about it -- the withDefault
* function doesn't have access to the map itself, so it can only produce a default value
* (but not save it). Also, the behavior of the WithDefault seems to be that it doesn't save
* the default value when accessed.
*
* My question is: is there a way to get this behavior, or do I have to implement it myself?
* In ruby, for example, the constructor block has access to the hash as well as the key:
*
* Hash.new { |hash, key| hash[key] = [] }
*
* Thanks!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment