如何在 Scala 2.11 中查找封闭源文件的名称

How to find the name of the enclosing source file in Scala 2.11

scala 2.11在编译时如何获取当前源文件(写代码的地方)的名称?

这里有一个实际可行的有点老套的方法:

val srcFile = new Exception().getStackTrace.head.getFileName
println(srcFile)

来源:How do I get the current script or class name in Scala?

在REPL中,名称是console,但是这表明一个位置知道它的来源。

scala> import scala.language.experimental.macros
import scala.language.experimental.macros

scala> import scala.reflect.macros.whitebox.Context
import scala.reflect.macros.whitebox.Context

scala> def f(c: Context): c.Tree = { import c._,universe._ ; Literal(Constant(c.enclosingPosition.source.file.name)) }
f: (c: scala.reflect.macros.whitebox.Context)c.Tree

scala> def g: String = macro f
defined term macro g: String

scala> g
res0: String = <console>

或者,你可以使用@li-haoyi的优秀sourcecode macro library

def foo(arg: String)(implicit file: sourcecode.File) = {
  println(s"this file is: '${file.getAbsolutePath}'")
}

foo("hello") // "this file is '/path/to/file'"

此外,还有许多其他好东西,例如行号、变量名称等。