Exploring Map Collections in Scala

Topic Overview and Actualization

Greetings, student! Today, we are studying the Map data structure in Scala. It functions like a dictionary, pairing a unique key with a corresponding value. Our primary focus will be on creating, accessing, and utilizing the unique properties of Maps in Scala.

Understanding Maps in Scala

In Scala, a Map stores key-value entries. Consider a dictionary where words are keys and definitions are values. This analogy parallels a Map's functioning: keys are unique, just as no two words have the same meaning.

Scala
@main def run: Unit =
  val animalHabitats = Map("Lion" -> "Savannah", "Penguin" -> "Antarctica", "Kangaroo" -> "Australia")
  println(animalHabitats) // prints Map(Lion -> Savannah, Penguin -> Antarctica, Kangaroo -> Australia)

In the above example, "Lion", "Penguin", and "Kangaroo" are the keys, and "Savannah", "Antarctica", and "Australia" are the values. The symbol -> is used to separate each key from its corresponding value.

Creating Maps in Scala

In Scala, Map can be either immutable or mutable. Immutable maps cannot be modified after they are created, meaning you cannot update the values of existing keys, add new keys, or remove existing keys. Mutable maps, on the other hand, allow for these modifications. To create an immutable map, we use Map(). For mutable maps, we use mutable.Map(). Note that working with mutable maps requires importing the scala.collection.mutable package. Importing is a way of adding additional functionalities to your program.

Scala
import scala.collection.mutable

@main def run: Unit =
  val immutableMap = Map("Sam" -> 23, "Amanda" -> 30, "Trevor" -> 29)
  println(immutableMap) // prints Map(Sam -> 23, Amanda -> 30, Trevor -> 29)

  val mutableMap = mutable.Map("Mary" -> 31, "Bob" -> 28, "Hannah" -> 27)
  println(mutableMap) // prints Map(Mary -> 31, Bob -> 28, Hannah -> 27)

This example illustrates how to define both immutable and mutable maps. Note that the import scala.collection.mutable statement is necessary to utilize mutable maps.

Working with Immutable Maps

Immutable maps cannot be changed once created. You can, however, access elements by their keys.

Scala
@main def run: Unit =
  val animalHabitats = Map("Lion" -> "Savannah", "Penguin" -> "Antarctica", "Kangaroo" -> "Australia")
  println(animalHabitats) // prints Map(Lion -> Savannah, Penguin -> Antarctica, Kangaroo -> Australia)
  println(animalHabitats("Penguin")) // prints Antarctica
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal