Get name of current function in Kotlin

I found one of the way:-

val name = object : Any() {

}.javaClass.enclosingMethod.name

Above code can also be refine as -

val name = object{}.javaClass.enclosingMethod.name

Edit because incorrect duplicate flag prevents a new answer:

A more Java way is this:

Thread.currentThread().stackTrace[1].methodName

but it takes ~47ms on my system compared with ~13ms for the object() based one: nearly 4 times slower.


There's also another option if you don't need the name to be discovered dynamically at runtime:

instance::method.name

Check below example on https://pl.kotl.in/1ZcxQP4b3:

fun main() {
    val test = Test()
    test.methodA()
    println("The name of method is ${test::methodA.name}")
}

class Test {
    fun methodA() {
        println("Executing method ${this::methodA.name}")
        println("Executing method ${::methodA.name} - without explicit this")
    }
}

After executing main() you will see:

Executing method methodA
Executing method methodA - without explicit this
The name of method is methodA

This way you can leverage all the "IDE intelligence" (renaming, searching for occurrences, etc.) but what's important, all occurrences of instance::method.name are replaced by Kotlin to ordinary strings during compilation. If you decompile Kotlin-generated bytecode, you'll see:

public final void main() {
    Test test = new Test();
    test.methodA();
    String var2 = "The name of method is " + "methodA"; // <--- ordinary string, no reflection etc.
    boolean var3 = false;
    System.out.println(var2);
}

Tags:

Android

Kotlin