Get companion or null from KClass

Hi everyone,

Is it possible to get the Companion Object instance from a given KClass without using Kotlin-Reflect-Full?

I know this is possible using Kotlin-Reflect-Full with the following method: companionObjectInstance. However, this Kotlin-Reflect-Full is a big library and I would like to avoid to add it to my app - I’m an Android Developer.

Another option I found is using AssociatedObjectKey + findAssociatedObject but this means that I would need to manually add this annotation with a reference to the companion object every time I want to do this… For more details about this approach, check here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/find-associated-object.html

Is there any other alternative? It would be super nice if it would be possible to get a companion instance without relying on Kotlin-Reflect-Full. :disappointed:

Thank you very much. :smile:

I’m pretty sure this is a feature that requires full reflection, so I don’t think there is any way around kotlin-reflect-full. Also AssociatedObjectKey + findAssociatedObject is a kotlin native only feature so you won’t be able to use that on android unless you want to switch to native and I don’t think that is worth it for that.

1 Like

It sounds like you’re trying to make a design mistake, since you really shouldn’t know anything about the companion objects that you would discover this way.

Perhaps you’d like to make a base class that these companion objects could subclass, and have each instance of the base class register itself somewhere.

1 Like