This article explores different ways to create a deep copy of a List of Objects in Kotlin.

1. Using Copy Constructor

The recommended approach to copy objects in Kotlin is using the copy constructor, which accepts the instance of the same class and creates a deep copy for all mutable fields. This is demonstrated below:

Download Code

Output:


User(name='User1', regDateTime=2018-12-30T18:00:00.00)
User(name='User2', regDateTime=2018-12-30T18:00:00.00)
User(name='User3', regDateTime=2018-12-28T18:00:00.00)

2. Implement Cloneable interface

To facilitate a field-by-field copy of a List of objects, we can iterate through the list and add a clone of each item to the new list. To create a clone of an object, have that object implement the Cloneable interface and override its clone() function.

Download Code

Output:


User(name='User1', regDateTime=2018-12-30T18:00:00.00)
User(name='User2', regDateTime=2018-12-30T18:00:00.00)
User(name='User3', regDateTime=2018-12-28T18:00:00.00)

3. Custom clone() function

We can also implement our own clone() function, instead of implementing the Cloneable interface and overriding its clone() function. This is demonstrated below:

Download Code

Output:


User(name='User1', regDateTime=2018-12-30T18:00:00.00)
User(name='User2', regDateTime=2018-12-30T18:00:00.00)
User(name='User3', regDateTime=2018-12-28T18:00:00.00)

That’s all about creating a deep copy of a List in Kotlin.