With Effective Java’s item 13 on cloning, it is clear to me that Joshua Bloch’s advice is to avoid the complexities of the clone method. Indeed, he suggests “a better approach to object copying is to provide a copy constructor or copy factory”.
Kotlin has taken this advice from Effective Java with the implementation of a
copy function when you create a
copy creates a new instance with the default constructor, avoiding a lot of the complexities of clone while additionally allowing overriding of any of its properties.
It is essential to understand how copy works, with reference types it is merely copying the reference to the object and not copying the content. Consider the following code:
data class Object(val list: List<Int>)
val list = mutableListOf(1)
val alex = Object(list)
val bob = alex.copy()
Although the class of
list may look immutable, you can, of course, provide any type including mutable lists. Given that
copy copies the reference when the mutable list changes we will see that both objects now contain
As with clone, be careful when dealing with mutable classes such as lists, and builders. Copy only works well on entirely immutable objects.