scalainspection

Is it possible to recover the name of the function from within the function in scala?


I'd like to do something like

def getMeASammy() {println "getMeASammy"}
def getMeADrink() {println "getMeADrink"}
def getMeASub() {println "getMeASub"}

But, I don't want to explicitly type out the name of the function.


Solution

  • scala> def currentMethodName() : String = Thread.currentThread.getStackTrace()(2).getMethodName
    currentMethodName: ()String
    
    scala> def getMeASammy() = { println(currentMethodName()) }
    getMeASammy: ()Unit
    
    scala> getMeASammy()
    getMeASammy