Here is the easiest way to deep copy an object in Kotlin

If you ever needed to deep copy an object in Kotlin you know what pain it can be. Every solution I've seen out there will point you towards data class because then you can use the copy() method, but the problem is: this method only creates shallow copies, which is useless if one of your object's properties is a collection of objects, for example.

So, what's the solution? Simple:

Use GSON to serialize the object to a JSON string then de-serialize it back to your class.

This trick works because when GSON serializes an object, it creates a string with a series of key-value pairs that represent the serialized object. But when you serialize that string using the same class structure, GSON will flawlessly copy all those values into a brand new object, thus eliminating any reference to the original object.

First, add GSON to your project:

dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}

Then, add this funcion to your class:

fun deepCopy():MyCustomClass {
val JSON = Gson().toJson(this)
return Gson().fromJson(JSON, MyCustomClass::class.java)
}

So your class will look like this:

class MyCustomClass{//your object propertiesfun deepCopy():MyCustomClass {
val JSON = Gson().toJson(this)
return Gson().fromJson(JSON, MyCustomClass::class.java)
}
}

So everytime you wish to deep copy an instance of your class, you just invoke the deepCopy() method:

var object1 = MyCustomClass()
var object2 = MyCustomClass()
object1 = object2.deepCopy()

Enjoy!

Written by

Produtor Musical, Compositor e Arranjador. Casado e pai de duas meninas. Desajustado e nerd.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store