Scala Collections Maps Tutorial

4/12/2025

Mutable vs immutable map scala

Go Back

Scala Collections Maps Tutorial

In Scala, Maps are one of the most widely used collection types, ideal for storing key-value pairs. Whether you're building a lookup table, configuring application settings, or managing a dataset, Maps provide powerful features and performance. In this tutorial, we'll explore everything from the basics of Maps to advanced operations and best practices.

 Mutable vs immutable map scala

What is a Map in Scala?

A Map in Scala is a collection of key-value pairs where each key is unique. Scala provides both immutable and mutable versions of Maps, catering to different programming needs.

val immutableMap = Map("a" -> 1, "b" -> 2)
var mutableMap = scala.collection.mutable.Map("x" -> 10, "y" -> 20)

By default, Map refers to an immutable map. If you need to update contents frequently, use the mutable version explicitly.

Mutable vs Immutable Map in Scala

In Scala, a Map is a collection of key-value pairs that allows fast data retrieval based on keys. Scala supports two types of Maps: immutable and mutable, catering to different programming paradigms and use cases.

By default, Scala favors immutable collections, aligning with functional programming principles. An immutable Map cannot be modified once it is created—any operation like adding or removing elements returns a new Map. This ensures thread safety and predictability in concurrent environments.

On the other hand, a mutable Map allows in-place updates, additions, and removals. It’s part of Scala’s mutable collection library and is more suited for use cases where performance and frequent updates are priorities.

Understanding the differences between mutable and immutable Maps is essential for writing efficient and idiomatic Scala code. In this article, we will explore their syntax, performance characteristics, and best practices for choosing the right one.

Creating Maps

Immutable Map

val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")

Mutable Map

import scala.collection.mutable
val scores = mutable.Map("Alice" -> 90, "Bob" -> 85)

Empty Map

val emptyMap = Map.empty[String, Int]

Accessing Elements

You can retrieve values using keys:

val capital = capitals("France") // Returns "Paris"

To avoid exceptions for missing keys, use get, getOrElse, or pattern matching:

capitals.get("Germany") // Returns Option[String]
capitals.getOrElse("Germany", "Not Found")

Adding and Updating Elements

Immutable Map

Returns a new Map:

val updated = capitals + ("Germany" -> "Berlin")

Mutable Map

Modifies the map in place:

scores("Charlie") = 88
scores += ("Dave" -> 92)

Removing Elements

Immutable

val newMap = capitals - "Japan"

Mutable

scores -= "Bob"

Iterating Over Maps

for ((country, city) <- capitals) {
  println(s"Capital of $country is $city")
}

Common Map Operations

  • keys: Returns all keys

  • values: Returns all values

  • contains(key): Checks if a key exists

  • map / filter / foreach: Functional transformations

capitals.map { case (k, v) => (k.toUpperCase, v) }
capitals.filter(_._1.startsWith("F"))

Working with Default Values

val safeMap = capitals.withDefaultValue("Unknown")
safeMap("USA") // Returns "Unknown"

Sorting Maps

While Maps are unordered by default, you can sort them:

val sorted = scala.collection.immutable.SortedMap("c" -> 3, "a" -> 1, "b" -> 2)

Nested Maps

Maps can also be nested:

val students = Map(
  "Alice" -> Map("Math" -> 90, "Science" -> 85),
  "Bob" -> Map("Math" -> 88, "Science" -> 92)
)

Conclusion

Scala Maps are a versatile and efficient way to manage key-value data. Understanding the differences between mutable and immutable Maps—and knowing how to leverage functional operations—can help you write safer, more expressive code. Whether you're a beginner or a seasoned Scala developer, mastering Maps is a key step in becoming fluent with the language's powerful collection framework.