Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of current function in Kotlin

Tags:

android

kotlin

Update

How can I get function name which is currently being execute using Kotlin?

I'm trying to get the function name of the function which is currently being execute as below but it's always coming as null

val funName = Object().`class`.enclosingMethod?.name; 
like image 806
Suryakant Sharma Avatar asked Jan 10 '18 06:01

Suryakant Sharma


People also ask

What does :: mean in Kotlin?

:: is just a way to write a lambda expression basically we can use this to refer to a method i.e a member function or property for example class Person (val name: String, val age: Int) Now we can write this to access the person which has the maximium age.

What is member function in Kotlin?

The first type of functions is called member functions. These functions are defined inside a class, object, or interface. A member function is invoked using the name of the containing class or object instance with a dot, followed by the function name and the arguments in parentheses.

What is infix function in Kotlin?

Kotlin allows some functions to be called without using the period and brackets. These are called infix methods, and their use can result in code that looks much more like a natural language. This is most commonly seen in the inline Map definition: map( 1 to "one", 2 to "two", 3 to "three" )


1 Answers

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.

like image 83
Suryakant Sharma Avatar answered Oct 05 '22 09:10

Suryakant Sharma