O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 33

The Devil Is in the Defaults

In many languages, assigning default values to entries in a map involves tedious, boilerplate code:

  import collection.mutable
  val accBalances = mutable.Map[String, Int]()
    // opening credit is linked to the account holder's name
  def getBalance(accHolder: String): Int = {
    if (!(accBalances isDefinedAt accHolder)) {
      accBalances += (accHolder -> accHolder.length)
    }
    accBalances(accHolder)
  }
    scala> println(getBalance("Alice"))
  5

Fortunately, you can eliminate this clutter in Scala (and avoid mutable maps as well!) by providing a default function:

  import collection.immutable
  val accBalances = immutable.Map[String, Int]() withDefault {
    newCustomer => newCustomer.length }
   scala> println(accBalances( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required