Learn
Maps
Creating an Immutable Map

An immutable map contains read-only entries that cannot be altered. Immutable maps are most commonly used when all of the required data already exists in the group, and no further modification is needed.

To declare an immutable map, we need to use the mapOf keyword followed by a pair of parentheses:

val/var mapName = mapOf(key1 to val1, key2 to val2, key3 to val3)
  • Within the parentheses must exist unique keys along with their corresponding values.
  • The to keyword is used to link each key to its value.
  • Each entry must be separated by a comma.

Note: The keys within a map must be unique, however, the values can duplicate.

To apply what we’ve learned so far, let’s create a map of instruments:

var instruments = mapOf("String" to "Cello", "Brass" to "Saxophone", "Woodwinds" to "Flute")

Printing the value of instruments will result in the following output:

println(instruments) // {String=Cello, Brass=Saxophone, Woodwinds=Flute}

Notice how…

  • Each key is linked to its value with an = as opposed to the to keyword used in the original declaration.
  • The map is wrapped in curly braces as opposed to square brackets or parentheses.

Instructions

1.

In the previous exercise, we saw the following legend on a map:

{valley=scorpions, creek=snakes, forest=bears}

This code represents the output of a Kotlin map. In Journey.kt, let’s write code to reproduce this output.

First, declare a variable, codeysMap, and assign it to an immutable map with the above key-value pairs.

2.

Next, wrap the name of the map in a println() statement to confirm that we’ve generated the expected output.

Folder Icon

Take this course for free

Already have an account?