kotlinreflectioncompanion-objectkotlin-reflectkotlin-companion

Why can I not access `::class.companionObject`?


I am trying to access the companion object of an unknown class with a known interface, given an instance of the class.

Code below:

class AccessTest() {
    companion object {
        val prop = 5
    }
    fun getComp() {
        print(this)
        print(this::class)
        print(this::class.companionObject) // Unresolved reference.
        print(this::class.companionObjectInstance) // Unresolved reference.
    }
}

inline fun <reified T> getCompanion() {
    print(T::class.companionObject) // Unresolved reference.
    print(T::class.companionObjectInstance) // Unresolved reference.
}

fun main() {
    AccessTest().getComp()
    getCompanion<AccessTest>()
}

Output:

$ kotlinc -d main.jar main.kt && kotlin -classpath main.jar MainKt
main.kt:8:27: error: unresolved reference: companionObject
        print(this::class.companionObject) // Unresolved reference.
                          ^
main.kt:9:27: error: unresolved reference: companionObjectInstance
        print(this::class.companionObjectInstance) // Unresolved reference.
                          ^
main.kt:14:20: error: unresolved reference: companionObject
    print(T::class.companionObject) // Unresolved reference.
                   ^
main.kt:15:20: error: unresolved reference: companionObjectInstance
    print(T::class.companionObjectInstance) // Unresolved reference.
                   ^

I do not think this is a duplicate of either of the below questions, as I am specifically asking what has changed or what I am misunderstanding such that the solution in the two below questions is not working for me:

how to access companion object from object instance in kotlin?

Kotlin invoke companion function with reflection


Solution

  • After a short discussion in comments, it turned out it was just a missing import.

    companionObject is not a member of KClass, but extension on it, so it is possible we have access to KClass object, but we don't see its companionObject property. Also, as it's the part of kotlin-reflect library, it is not located in kotlin.reflect package, but in kotlin.reflect.full, so importing kotlin.reflect.* isn't enough to get it.