lundi 1 novembre 2021

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





Aucun commentaire:

Enregistrer un commentaire