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;
:: 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.
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.
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" )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With