Friday, January 24, 2020

Updating a mutable map counter value


val symTab = collection.mutable.HashMap[String, Int]()
def update0(s: String): Unit = {
  if (symTab.contains(s)) {
    symTab(s) = symTab(s) + 1
  }
  else {
    symTab(s) = 1
  }
}

// Do this instead
def update1(s: String): Unit = symTab(s) = symTab.getOrElse(s, 0) + 1

scala> update1("x")

scala> symTab("x")
res2: Int = 1

scala> update1("x")

scala> symTab("x")

res4: Int = 2

No comments:

Post a Comment