Is it possible to recover the name of the function from within the function in scala?
scala> def currentMethodName() : String = Thread.currentThread.getStackTrace()(2).getMethodName
currentMethodName: ()String
scala> def getMeASammy() = { println(currentMethodName()) }
getMeASammy: ()Unit
scala> getMeASammy()
getMeASammy
It's somewhat revolting, but the only supported way to get the name of the current method from the JVM is to create an exception (but not throw it), and then read the method name out of the exception's stack trace.
def methodName:String= new Exception().getStackTrace().apply(1).getMethodName()
I wrote a simple library, which is using a macro to get the name of the function. It might be a more elegant solution than using Thread.currentThread.getStackTrace()(2).getMethodName
if you don't mind additional dependency:
libraryDependencies += "com.github.katlasik" %% "functionmeta" % "0.2.3" % "provided"
import io.functionmeta._
def getMeASammy() {
println(functionName) //will print "getMeASammy"
}