Creating an instance of a KClass

Hello. Didn’t find this topic and the case is simple: currently it’s not possible to inherit data class from another one and its copy method is not deep. (The common method is to serialize/parcelize the class and return back, but it’s another story). So, I’m trying to simply create a new instance of a KClass according to these methods but can’t find such as:

  • primaryConstructor
  • createInstance
    and .constructors.first().call() doesn’t work even if my class have no constructor parameters (or they have defaults)

So, if MyClass::class.java.newInstance() is the best method, is there a purpose to use others? It’s even doesn’t need to add ‘reflect’ in gradle. (Maybe there is something for KMP but not sure).

P.S. is there a shorten way to get KCLass from an instance instead of foo.javaClass.kotlin?

foo::class

To digress for a moment…

I was going to add that technically, ::class doesn’t create a KClass instance, but simply returns the existing one representing that class. However, having checked, I’m not so sure!

In Java, that’s how Class works: it’s a class with a private constructor, so you have no way to create new instances, and can only use the ones you get from .class and similar — which are presumably created by the JVM when first loading the class class, and so there’s exactly one instance for each class.

But Kotlin’s KClass is not a class — it’s an interface. And you can create your own objects implementing it (though it’s a bit fiddly, with 19 separate properties to implement).

Does anyone know why it was done that way? And what effects that might have on code using it?

1 Like

It’s an interface just because there’s multiple implementations of it due to a KClass having multiple implementations depending on the situation (I think e.g. classes defined in Java might have a different KClass impl or something, I don’t know tbh)

I don’t have an IDE in front of me right now, but IIRC, when you decompile kotlin code that uses foo::class (by using Show Kotlin Bytecode and decompile to Java) it calls an intrinsic method like getOrCreateKClass(foo.class), and so internally it has some map of Java Classes to KClasses

1 Like