Mike Slinn
Mike Slinn

Using Scala’s String Interpolation to Access a Map

Published 2013-03-15.
Time to read: 1 minutes.

This page is part of the posts collection, categorized under Scala.

Given a map, would it not be nice to have a shorthand way of looking up a value from a key, and to provide a default value? I’ve wanted to be able to do this for a long time. Scala 2.10 makes this really easy!

The MapLookup class below contains a Map[String, Int] that can be looked up by using a dollar sign ($) from code that contains a reference to the implicit class. If the lookup key is not defined by the map, a zero is returned.

Shell
implicit class MapLookup(val sc: StringContext) {
  val map = Map(("a", 1), ("b", 2), ("c", 3)).withDefaultValue(0)
def $(args: Any*): Int = { val orig = sc.s (args : _*) map.get(orig) } }

Assuming that the above is stored in a file called strInterp.scala, here are some examples of usage:

Shell
$ scala -i strInterp.scala
Loading strInterp.scala...
defined class MapLookup
Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_17). Type in expressions to have them evaluated. Type :help for more information.
scala>
$"a" res2: Int = 1
scala>
$"z" res3: Int = 0

Short and sweet!



* indicates a required field.

Please select the following to receive Mike Slinn’s newsletter:

You can unsubscribe at any time by clicking the link in the footer of emails.

Mike Slinn uses Mailchimp as his marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp’s privacy practices.