Is it possible to get the instance of the companio...
# announcements
Is it possible to get the instance of the companion object of an inheriting class?
No? You can’t guarantee, through inheritance or otherwise, that a class will have a companion object
well, i don't need it to be compile-time guaranteed. i'll personally guarantee it has one.
it'd be nice if we could use companion classes as factories
@Hullaballoonatic How about this:
Copy code
sealed class ParentClass {

    fun getSubclasses() {
        val sealedSubclasses = ParentClass::class.sealedSubclasses
//        println(sealedSubclasses.toList().toString())

        val nestedClasses = sealedSubclasses[0].nestedClasses
        println((nestedClasses.toList()[0].objectInstance as ChildClass.Companion).TEST)

    class ChildClass : ParentClass() {

        companion object {
            const val TEST = "test"


This does what you want, I think. Not sure if there's way of getting an instance without type-casting and this is only for sealed sub-classes.
Actually you could do this further:
Copy code
val nestedClasses = sealedSubclasses[0].nestedClasses
        val nestedClass = nestedClasses.toList()[0]
        val members = nestedClass.members.toList()
        val testConst = members[0]
And get the value of
const. Calling a function might be slightly more difficult.
👍 1