Maps

Understand the map data structure, its use cases, and how to put it to use in Kotlin.

A map is a collection of keys associated with values. This is a concept you may also know as dictionaries (e.g., Python) or associative arrays (e.g., PHP). Each key is associated with one unique value. This value can have any type. In particular, it may be a collection, such as a list or a nested map.

Creating a Map #

Once again, Kotlin provides a convenient way to initialize (read-only) maps:

Press + to interact
val grades = mapOf(
"Kate" to 3.9,
"Jake" to 3.4,
"Susan" to 3.5
)

This map associated the key "Kate" to the value 3.9, "Jake" to 3.4, and so on.

Pairs and Infix Functions #

The to function is a so-called infix function, a concept which we’ll cover later in this course. It returns a Pair, which is a simple data structure containing exactly two values. Therefore, you can also initialize the array above using Pairs directly:

val grades = mapOf(
  Pair("Kate", 3.9),
  Pair("Jake", 3.4),
  Pair("Susan", 3.5)
)

Kotlin makes this initialization more convenient and readable by providing the to function.

From now on, it will be important to ...