This article explores different ways to clone a list in Kotlin.

1. Using Copy Constructor

A simple and efficient solution is to use a copy constructor to clone a list, which creates a new object as a copy of an existing object.

Download Code

2. Using addAll() function

You can also use the addAll() function that appends all the given list elements at the end of a new list.

Download Code

 
This can be shortened using the apply() function:

Download Code

3. Using toCollection() function

Another solution is to use the toCollection() function, which appends all elements to the given destination collection.

Download Code

4. Using mutableListOf() function

You can also use the toList() or toMutableList() function to create a copy of a collection. Although, there is no official documentation that guarantees that this function returns a new copy of the list.

Download Code

5. Implement the Cloneable Interface

If you’re dealing with a list of objects, you can have the class implement the Cloneable interface and override its clone() function.

Download Code

6. Using Data class

If your list is storing objects of a data class, you can use the copy() function derived by the compiler.

Download Code

That’s all about cloning a list in Kotlin.