11.12. Creating Maps

Problem

You want to use a mutable or immutable Map in a Scala application.

Solution

To use an immutable map, you don’t need an import statement, just create a Map:

scala> val states = Map("AL" -> "Alabama", "AK" -> "Alaska")
states: scala.collection.immutable.Map[String,String] =
  Map(AL -> Alabama, AK -> Alaska)

This expression creates an immutable Map with type [String, String]. For the first element, the string AL is the key, and Alabama is the value.

As noted, you don’t need an import statement to use a basic, immutable Map. The Scala Predef object brings the immutable Map trait into scope by defining a type alias:

type Map[A, +B] = immutable.Map[A, B]
val Map         = immutable.Map

To create a mutable map, either use an import statement to bring it into scope, or specify the full path to the scala.collection.mutable.Map class when you create an instance. You can define a mutable Map that has initial elements:

scala> var states = collection.mutable.Map("AL" -> "Alabama")
states: scala.collection.mutable.Map[String,String] = Map(AL -> Alabama)

You can also create an empty, mutable Map initially, and add elements to it later:

scala> var states = collection.mutable.Map[String, String]()
states: scala.collection.mutable.Map[String,String] = Map()

scala> states += ("AL" -> "Alabama")
res0: scala.collection.mutable.Map[String,String] = Map(AL -> Alabama)

Discussion

Like maps in other programming languages, maps in Scala are a collection of key/value pairs. If you’ve used maps in Java, ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.