This article covers different ways to get name of the current function being executed in Kotlin.

1. Using Class.getEnclosingMethod() function

The trick is to call the Class.getEnclosingMethod() that returns a java.lang.reflect.Method object with almost every bit of information on immediately enclosing the underlying class’s function.

Download Code

Output:

The current function is main

 
You can also define an inner class within a function to get Class reference, as shown below:

Download Code

Output:

The current function is main

2. Using Throwable.getStackTrace() function

Another approach is to get an array of stack trace elements representing the stack trace pertaining to a throwable by calling getStackTrace() on a Throwable instance.

The first element of the array represents the top of the stack, which is the last function invocation in the sequence.

Download Code

Output:

The current function is main

 
You can also use the Exception class, which extends Throwable.

Download Code

Output:

The current function is main

3. Using Thread.getStackTrace() function

Another plausible way is to use the stack trace of a current thread, which returns an array of stack trace elements representing the stack dump of this thread.

The second element of the returned array of stack trace contains the stack frame of the current function.

Download Code

Output:

The current function is main

That’s all about getting the name of the current function in Kotlin.