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.
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.
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.
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.
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.
Immutable maps cannot be changed once created. You can, however, access elements by their keys.
Mutable maps allow us to add, update, and remove elements dynamically. To add or update a key-value pair, use the syntax map(<key>) = <value>
. To remove elements, use the -=
operator.
Maps
offer useful properties. size
denotes the number of entries, keys
return all keys, and values
list all values present in a Map
. Additionally, methods such as head
, tail
, last
, and contains
that were used for Set
in the previous lesson also work for Map
. Note that head
, tail
, and last
don't guarantee any specific order for the elements. These properties and methods work for both mutable and immutable maps.
Great! You've explored Maps
in Scala. You learned how to create immutable and mutable maps, access and modify their elements, and use various properties and methods to interact with them. Armed with this knowledge, you're ready to dive into the practice sessions and reinforce these concepts. Keep going!
