I just found that I need to create a copy of an object (out Any
) if it is possible. In kotlin java clone
method is protected by default so I can’t just clone it if it implements Cloneable
interface. I think it is a good solution since java clone
was not useful anyway.
If I do understand correctly, the kotlinish way of doing that is to use data classes with copy
method. It seems that it is not possible to check if objects implements data class in runtime and also to cast it to data class and use copy
method. Since data classes are generated during compilation, I think it should be possible to add marker interface to them like:
interface DataClass<C>{
fun copy() : C
}
and force any data class to automatically implement it. Then I can not only check for data class in runtime, but also safely copy it.
I understand about reflections, still it won’t help in my case since I want to use copy
method. I can’t upcast my class to data class because I need to know specific class name. The only thing I really can do is call copy
via reflections which is quite ugly in my opinion.
My suggestion is to consider adding marker interface to all data classes. It should not break backward compatibility. The alternative is to use another cloning mechanism, but using only data classes for cloning seems a quite elegant solution.
You still have to deal with the fact that in that case you can only access the copy method dynamically using reflection (or method reference). Suppose that all data classes implemented a Copyable
interface, it wouldn’t work as each copy function is different (although it has parameter default values for all parameters). The only think you would get is the no-arg overload. Perhaps it would be worthwhile to actually amend Data classes to also generate a no-arg copy function officially.
In my example I’ve used no-arg copy so it is possible. I understand that due to type erasure it is not possible to completely solve clone problem in JVM, still there are places when clone is unavoidable.
I think it is a good solution to allow clones (or copies) only for data classes since that’s what data classes are for. But it requires some additional tinkering to expose data class copy
method to unaware caller.