Get file name of current file in scala

Is there any way the file name of the current file (when the code is written) in scala?

How my class is in a file, for example com / mysite / app / myclass.scala, and I want to call a method that will return "myclass.scala" (or the full path ...)

Thank!

+3
source share
1 answer

This can be achieved with Scala macros , an experimental language feature available from version 2.10.

Macros allow you to interact with the AST building during the parsing phase of the source code and modify the AST trees until the actual compilation is complete.

, Context, String, AST.

. :

, :

// Contents of: "Macros.scala"

import scala.reflect.macros.Context
import scala.language.experimental.macros

object Macros {
    def sourceFile: String = macro sourceFileImpl
    def sourceFileImpl(c: Context) = {
        import c.universe._
        c.Expr[String](Literal(Constant(c.enclosingUnit.source.path.toString)))
    }
}

, :

// Contents of: "Main.scala"

object Main extends App {
    val fileName = Macros.sourceFile
    println(fileName)
}

. , .

+4

All Articles