Skip to content
DeveloperMemos

How to Clone an Object in Kotlin

Kotlin, Cloning, Object1 min read

Cloning an object in Kotlin is the process of creating a new object that has the same values as an existing object. There are several ways to achieve this in Kotlin, and each has its pros and cons. In this article, we'll cover the most common methods for cloning an object in Kotlin.

  1. Copy Constructor

A copy constructor is a constructor that creates an object by copying values from an existing object. In Kotlin, you can create a copy constructor by using the copy keyword. Here's an example:

1data class Person(val name: String, val age: Int) {
2 fun copy(name: String = this.name, age: Int = this.age) = Person(name, age)
3}

With this code, you can create a new Person object with the same values as an existing Person object using the following code:

1val originalPerson = Person("John", 25)
2val clonedPerson = originalPerson.copy()
  1. Object Serialization

Another way to clone an object in Kotlin is by serializing and deserializing the object. This method works by converting the object into a byte stream, then creating a new object from the byte stream. Here's an example:

1import java.io.*
2
3fun main() {
4 val originalPerson = Person("John", 25)
5
6 val baos = ByteArrayOutputStream()
7 val oos = ObjectOutputStream(baos)
8 oos.writeObject(originalPerson)
9 oos.close()
10
11 val bais = ByteArrayInputStream(baos.toByteArray())
12 val ois = ObjectInputStream(bais)
13 val clonedPerson = ois.readObject() as Person
14 ois.close()
15}
  1. copyTo Function

The copyTo function is a convenient way to copy values from one object to another. Here's an example:

1data class Person(var name: String, var age: Int)
2
3fun main() {
4 val originalPerson = Person("John", 25)
5 val clonedPerson = Person("", 0)
6 originalPerson.copyTo(clonedPerson)
7}

In this example, the copyTo function copies the values from the originalPerson object to the clonedPerson object.

Conclusion

Cloning an object in Kotlin can be achieved using a copy constructor, object serialization, or the copyTo function. The method you choose will depend on your specific requirements and constraints. In general, the copy constructor is the simplest and most efficient way to clone an object in Kotlin. However, for more complex objects, object serialization or the copyTo function may be more appropriate.