This article explores different ways to initialize a map in Kotlin.

1. Using mapOf() function

The mapOf() function returns an unmodifiable map from given key/value pairs, which does not permit subsequent addition or removals.

Download Code

2. Using mutableMapOf() function

To get a mutable map of the given key/value pairs, you can use the mutableMapOf() function.

Download Code

3. Using hashMapOf() function

To get a Hashmap instance, use hashMapOf() function. If you need LinkedHashMap, use linkedMapOf() function instead.

Download Code

4. Using emptyMap() function

To get an immutable empty map, consider using emptyMap() function.

Download Code

5. Using Map.of() function

Java 9 made it very convenient to create a compact, unmodifiable instance of a map by providing static factory methods on the java.util.Map interface.

Download Code

6. Using Double Brace Initialization

Another alternative is to use Double Brace Initialization, which creates an anonymous inner class with an instance initializer.

Download Code

That’s all about initializing a map in Kotlin.