, 0__, , , :
package utils
trait ProgramInfo {
val programInfo = try {
throw new RuntimeException("x")
} catch {
case e: RuntimeException =>
val arr = new java.io.CharArrayWriter()
val buffer = new java.io.PrintWriter(arr)
e.printStackTrace(buffer)
val trace = arr.toString
val lines = io.Source.fromString(trace)
val pat = """^.*at.*\.main\(([^:]*)(:.*)?\).*$""".r
lines.getLines().collectFirst{case pat(n, l) => n}.getOrElse("<none>")
}
}
object ProgramInfo extends ProgramInfo
:
println(utils.ProgramInfo.programInfo)
object A extends utils.ProgramInfo {
def main(args: Array[String]) {
println(programInfo)
}
}
This works for scripts scala A.scriptwhether the code is enclosed in an object or not. This also works when compiling with scalacand runs as scala A. When launched from REPL, this will return <none>.
source
share