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

Jija picture Jija · Jun 23, 2010 · Viewed 7k times · Source

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.

Answer

Richard Fearn picture Richard Fearn · Jun 23, 2010
scala> def currentMethodName() : String = Thread.currentThread.getStackTrace()(2).getMethodName
currentMethodName: ()String

scala> def getMeASammy() = { println(currentMethodName()) }
getMeASammy: ()Unit

scala> getMeASammy()
getMeASammy