Is it possible to get the instance of the companio...
# announcements
h
Is it possible to get the instance of the companion object of an inheriting class?
s
No? You can’t guarantee, through inheritance or otherwise, that a class will have a companion object
h
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
a
@Hullaballoonatic How about this:
ClassName::class.sealedSubclasses[0].nestedClasses
:
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"
        }

    }
}

ParentClass.ChildClass().getSubclasses()
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]
        println(testConst.call(this))
And get the value of
TEST
const. Calling a function might be slightly more difficult.
👍 1