Ad space (banner)
Lesson 10 / 20

Working with maps (Map)

This lesson covers the map, which manages data as key-value pairs.

Writing Map(key -> value, ...) creates a structure where you look up a value by its key. It corresponds to a dictionary or associative array in other languages.

The sample code builds a map of products and prices — val prices = Map("apple" -> 100, "orange" -> 80) — and reads a value out with prices("apple").

A common early stumble is that reaching for a key that does not exist throws an exception. To read a value safely, the usual approach is the get() method, which uses the Option type covered in the next lesson.

In professional work, maps come up constantly for managing configuration values and for grouping aggregated results by key.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)