How to get KCallable from extension function?

I have two classes, Foo and Bar.

class Foo

class Bar

With a normal method inside Bar, I can get the name of that method using reflection, like so:

class Bar {
    fun doThing1() {}

    fun doThing2() {
        println(::doThing1.name)
    }
}

However, if I have a function inside Bar that is an extension function on Foo, that syntax no longer works:

class Foo

class Bar {
    fun Foo.doFooThing() {}

    fun doThing2() {
        println(::doFooThing.name) // does not work, unresolved reference
        println(Foo::doFooThing.name) // 'doFooThing' is a member and extension at the same time. References to such elements are not allowed.
    }
}

Is there a way to get the name of my extension method via reflection?

You can use kotlin.reflect.full.memberExtensionFunctions:

this::class.memberExtensionFunctions.single { it.name == "doFooThing" }

Issue for this problem: KT-8835.

1 Like

Yeesh… it’s an option, but a very verbose and ugly one. xD It also entirely defeats the purpose of what I’m trying to do, which is to always have the correct function name, in the event that the function gets renamed; using a reflective reference (thanks to IntelliJ’s top-tier refactoring tools) means the reference to the function will be updated as well. :slight_smile:

Thanks for the link to the YouTrack issue; I’ve added a vote for it, though I’m guessing it probably won’t get done for a very long time (if ever) based on the lack of votes for it. :stuck_out_tongue: