sinedsem sinedsem - 2 months ago 15
Scala Question

How to use getOrElseUpdate in scala.collection.mutable.HashMap?

The example code counts each word's occurrences in given input file:

object Main {
def main(args: Array[String]) {
val counts = new scala.collection.mutable.HashMap[String, Int]
val in = new Scanner(new File("input.txt"))

while (in.hasNext()) {
val s: String = in.next()
counts(s) = counts.getOrElse(s, 0) + 1 // Here!
}

print(counts)
}
}


Can the highlighted with comment line be rewritten using the
getOrElseUpdate
method?

P.S. I am only at the 4th part of the "Scala for the impatient", so please don't teach me now about functional Scala which, I am sure, can be more beautiful here.

Thanks.

Answer

If you look at the doc you'll see the next:

If given key is already in this map, returns associated value. Otherwise, computes value from given expression op, stores with key in map and returns that value.

, but you need to modify map anyway, so getOrElseUpdate is useless here.

You can define default value, which will return if key doesn't exist. And use it the next way:

import scala.collection.mutable.HashMap
object Main {
  def main(args: Array[String]) {
    val counts = HashMap[String, Int]().withDefaultValue(0)
    val in = new Scanner(new File("input.txt"))

    while (in.hasNext()) {
      val s: String = in.next()
      counts(s) += 1
    }

    print(counts)
  }
}