Detect data class in runtime


#1

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.


#2

See this question: https://stackoverflow.com/questions/29069988/is-there-a-way-to-identify-a-kotlin-data-class-from-a-regular-kotlin-class

It’s suggested to use kotlin reflection to check whether a class is a data class.


#3

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.


#4

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.


#5

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.