

In other words, to print Bob’s number, we would write phoneBook. When we need to access an item in the map, we use the index operator and put the key inside of the operator. Each pair is written key to value so in our example, “Bob Belcher” to 8675309 or “Linda Belcher” to 8675309. We create a phoneBook object using the mapOf(), or mutableMap(), and then specifying any number of pair arguments. Val phoneBook = mapOf("Bob Belcher" to 8675309, "Linda Belcher" to 8675310) In Kotlin, we could make such a map like so:

In the phone book example, we can think of a person’s name as the key and the phone number as the value. When we want to call somebody, and we only know their name but not their phone number, we find their name in the phone book and the phone book has their number associated with a name. It’s easy to think of a map being like a phone book.

When we lookup values in a map, we specify a key and the map returns an associated value. In the next tutorial we will discuss about sets in Kotlin.Maps are data structures that associate keys with values. In this tutorial we discussed about immutable and mutable maps, their creation using mapOf() and mutableMapOf() functions and some important functions provided.

Let us create immutable map using these two functions: fun main() The mapOf() is used to create a specific map with keys and values of K and V data types respectively. Similar to lists, the mapOf() function is used to create a general map where key and value can be of any data type. In Kotlin immutable maps are created using mapOf() and mapOf() functions. Immutable maps are created using Map interface. In Kotlin we can have both a mutable map and an immutable map. The to keyword is used to map a key to a value.Ī key value pair is also known as an entry. The key and value can be of different data type. The key should be unique and only one value can be stored for each unique key. Maps are used to store key and value pairs. In this tutorial we will discuss about Kotlin Map.
