Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala HashMap of Lists: simpler default?

I need a HashMap of Lists. Normally I do this:

val lists = mutable.HashMap[String,List[Int]]() { 
  override def default(key: String) = {
    val newList = List[Int]()
    this(key) = newList
    newList
  }
}

so that I can then simply write things like

lists("dog") ::= 14

without having to worry about whether the "dog" List has been initialised yet.

Is there a cleaner way to do this? I find myself typing out those five default override lines again and again.

Thanks!

like image 487
Perfect Tiling Avatar asked Jan 08 '13 19:01

Perfect Tiling


1 Answers

What about withDefaultValue()?

val lists = new mutable.HashMap[String,List[Int]].withDefaultValue(Nil)

lists("dog") ::= 13
lists("cat") ::= 14
lists("dog") ::= 15  //(13, 15)

See also

  • How to implement Map with default operation in Scala
like image 52
Tomasz Nurkiewicz Avatar answered Oct 29 '22 11:10

Tomasz Nurkiewicz