Scala HashMap of Lists: simpler default?

陌路散爱 提交于 2019-12-07 03:13:16

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/14222292/scala-hashmap-of-lists-simpler-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!