What is a Map?

A map keeps a collection of key-value pairs. Much like the way Kotlin provides a read-only immutable interface and a read-write mutable interface for the JDK List, the language also provides two interfaces for the JDK Map. All methods of the JDK Map interface are available through the mutable interface, and the read-only methods are available through the immutable interface.

Creating maps in Kotlin

You may use mapOf() to create a map and get a reference to the read-only interface Map<K, V>. Alternatively, use mutableMapOf() to get access to MutableMap<K, V>. Also, you may obtain a reference to the JDK HashMap using hashMapOf(), LinkedHashMap using linkedMapOf(), and SortedMap using sortedMapOf().

Let’s create an example using the immutable/read-only interface Map<K, V> and look at ways to access the elements. Here’s a piece of code to create a map of site names and their corresponding URLs, where both keys and values are Strings:

Get hands-on with 1400+ tech skills courses.