This article explores different ways to clone a map in Kotlin. The solution should create a copy of all the mappings from the given map to the new map.

1. Using toMap() function

You can use the native methods toMap() and toMutableMap() to return a copy of a map. The toMap() function returns an immutable instance of the map, while toMutableMap() function returns a mutable instance.

Download Code

2. Using Copy Constructor

Another simple and fairly efficient solution is to use the HashMap‘s copy constructor, which creates a new map as a copy of an existing map.

Download Code

3. Using putAll() function

Alternatively, you can also use the putAll() function to copy all mappings from the original map to an empty map.

Download Code

4. Custom Routine

Finally, you can write your own routine for this simple task. The idea is to iterate over the map and add each mapping from key K to value V in the specified map.

Download Code

That’s all about cloning a map in Kotlin.