0

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?

  • 1
    Does [this](https://stackoverflow.com/q/26578517/5133585) answer your "why" question? You say what you are trying to do isn't supported by data classes, what is it exactly? Perhaps there is a way to work around it if you are more specific. – Sweeper Dec 25 '22 at 12:46
  • You can use [Kotlinx Serialization](https://kotlinlang.org/docs/serialization.html) for serialization, which doesn't rely on reflection and works on all Kotlin platforms. – aSemy Dec 25 '22 at 13:22
  • Java's cloning and serialisation are a bit clunky; they date from the early days of the language, and I strongly suspect that if they were added later they would have been done rather differently — but by then the language was stuck with them (because it values backward compatibility very highly). For example, cloneability is indicated by a ‘marker interface’ (`Cloneable`), which has no methods, and indicates almost nothing to the user — instead, it indicates something to whatever is _implementing_ the clone function… (contd) – gidds Dec 26 '22 at 11:42
  • …And `clone()` is a method on `Object`, but is not supported by most classes… It's a bit of a mess, really. Kotlin is arguably doing a favour by hiding it; copy-constructors, `copy()` methods, and serialisation are arguably better approaches to cloning. And of course, it's only available on the JVM anyway, whereas those other approaches are cross-platform. – gidds Dec 26 '22 at 11:45

1 Answers1

0

It's disallowed in Kotlin.

You should implements Cloneable and override clone() or use data class.