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

At compile time, how to get the name of the current source file (where the code is written) in scala 2.11?

+5
source share
3 answers

In REPL, the name is console, but this indicates that the position knows its source.

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>
+4
source

Here is a kind of hacker way that actually does the trick:

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

Source: How to get the current script or class name in Scala?

+5
source

@li-haoyi

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

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

, , , ..

+1

All Articles