Start learning free

LESSON 106 OF 414 · DICTIONARIES

Dictionaries in Scala: Creating a Map

Lesson Read the full explanation

A Scala Map stores key-value pairs. Each key maps to one value.

val ages = Map("Ana" -> 12, "Ben" -> 15)
println(ages("Ana"))

Assignment
Follow the Coding Tutorial and practice using maps.


Hint
Use key -> value pairs when creating a map.


STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · DICTIONARIES

    Dictionaries in Scala, explained

    What a Map is

    A dictionary stores values under keys. Scala's version is the Map: a collection of key-value pairs where each key appears once and maps to one value. You look a value up by its key instead of by a position, which makes a map the right tool for things like names to scores or countries to capitals.

    A pair is written key -> value. The arrow builds a two-element tuple, and Map(...) takes any number of pairs:

    val ages = Map("Ana" -> 12, "Ben" -> 15)
    println(ages("Ana"))   // 12
    

    The type of ages is Map[String, Int]: keys are Strings and values are Ints. Scala works the type out from the pairs.

    Immutable and mutable maps

    Without any import, Map means scala.collection.immutable.Map. It can't be changed after creation: operations that "update" it return a new map. The mutable version lives in scala.collection.mutable and can be changed in place.

    The lesson uses the mutable one, because later lessons update and extend it:

    val scores = scala.collection.mutable.Map("Alice" -> 95, "Bob" -> 87, "Charlie" -> 72)
    

    The lesson writes the full package name because the file doesn't import the mutable Map. If you did write import scala.collection.mutable, you could shorten it to mutable.Map(...), and the name Map would still mean the immutable one.

    The exercise

    The task is a single declaration: a val named scores holding a mutable map with three entries, "Alice" to 95, "Bob" to 87 and "Charlie" to 72.

    1. Start with val scores =.
    2. Call scala.collection.mutable.Map(...).
    3. Inside the parentheses, write the three pairs separated by commas, each as "name" -> number.
            val scores = scala.collection.mutable.Map("Alice" -> 95, "Bob" -> 87, "Charlie" -> 72)
    

    The type is inferred as scala.collection.mutable.Map[String, Int].

    Good to know

    • val with a mutable map. val stops you from pointing scores at a different map. It doesn't stop the entries from changing, which is why a val is the usual choice here.
    • Keys are unique. If a key appears twice, the later pair wins: Map("a" -> 1, "a" -> 2) has one entry, a -> 2, and a size of 1.
    • Printing order. A mutable map is a hash map, and it doesn't promise to print in the order you wrote the pairs. For example, println(scores) shows HashMap(Bob -> 87, Alice -> 95, Charlie -> 72). Don't rely on the order of entries.
    • An empty map needs its types written out, because there are no pairs to infer them from: scala.collection.mutable.Map[String, Int]().
    • Key types. All keys share one type and all values share one type. Mixing "Alice" -> 95 with "Bob" -> "high" makes the value type a common supertype, which is rarely what you want.

    Where this goes next

    Once a map exists, three things matter most, and the next lessons cover them one at a time:

    • Reading a value by writing the key in parentheses, scores("Alice").
    • Changing a value with an assignment such as scores("Alice") = 99, which works because the map is mutable.
    • Counting entries with scores.size, which is 3 for the map above.

    Because the keys are strings here, spelling and capitalisation matter: "alice" is a different key from "Alice".

    Key takeaways

    • A Map holds key-value pairs written key -> value, with unique keys.
    • The default Map is immutable; use scala.collection.mutable.Map to change entries in place.
    • Don't depend on the order in which a map's entries are printed or visited.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free