Mike Slinn

Connoisseur of Technology

Using Scala 2.10's String Interpolation to Access a Map

2013-03-15 / All Blog posts

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.

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 : _*)

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

$ 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!

Contact Mike Slinn

Unless you are a recruiter, in which case you should not try to make contact!

  • Email
  • Direct: 514-418-0156
  • Mobile: 650-678-2285


The content on this web site is provided for general information purposes only and does not constitute legal or other professional advice or an opinion of any kind. Users of this web site are advised to seek specific legal advice by contacting their own legal counsel regarding any specific legal issues. Michael Slinn does not warrant or guarantee the quality, accuracy or completeness of any information on this web site. The articles published on this web site are current as of their original date of publication, but should not be relied upon as accurate, timely or fit for any particular purpose.

Accessing or using this web site does not create a client relationship. Although your use of the web site may facilitate access to or communications with Michael Slinn via e-mail or otherwise via the web site, receipt of any such communications or transmissions does not create a client relationship. Michael Slinn does not guarantee the security or confidentiality of any communications made by e-mail or otherwise through this web site.

This web site may contain links to third party web sites. Monitoring the vast information disseminated and accessible through those links is beyond Michael Slinn's resources and he does not attempt to do so. Links are provided for convenience only and Michael Slinn does not endorse the information contained in linked web sites nor guarantee its accuracy, timeliness or fitness for a particular purpose.

comments powered by Disqus

© 1976-2020, Michael Slinn. All rights reserved.