In Java, each object has a predefined .clone()
method that generates a copy of the object. I'm wondering why there isn't such a method in Kotlin.
I'm aware that there are specific cases such as .copy()
in data classes and .toList()
, .toSet()
, etc. for collections, but sometimes I'd like a default solution for a simple class.
For example, let's say I have a class like the following:
class SomeClass {
val intParam: Int
val strParam: String
}
Let's say I need to have functionality that data class
does not support. A shallow copy, such as what Java's .clone()
provides, would be sufficient. However in Kotlin, I should write, even for this simple case, 5 or so lines of purely utility code, which distracts focus from the main logic.
And if I have more complex parameters (and thus the necessity to copy deeply), I should write such utility code for all the classes in question.
Is there a simple solution that I am missing?