且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

运行“.scala"程序时,Scala 运行时/REPL 背后到底发生了什么?

更新时间:2022-01-24 00:19:08

是的,有一个 hello.class 生成.编译器会将你的代码包装在一个 Main 对象中,编译它然后执行 Main.main,给定 hello.scala 的

Yes, there is a hello.class generated. The compiler will wrap your code inside a Main object, compile it then execute Main.main, given hello.scala of

println(args.mkString)
println(argv.mkString)

如果您使用 -Xprint:parser 选项运行:scala -Xprint:parser hello.scala foo bar,您将看到代码是如何被重写的:>

If you run with the -Xprint:parser option: scala -Xprint:parser hello.scala foo bar you'll see how the code gets rewritten:

package <empty> {
  object Main extends scala.ScalaObject {
    def <init>() = {
      super.<init>();
      ()
    };
    def main(argv: Array[String]): scala.Unit = {
      val args = argv;
      {
        final class $anon extends scala.AnyRef {
          def <init>() = {
            super.<init>();
            ()
          };
          println(args.mkString);
          println(argv.mkString)
        };
        new $anon()
      }
    }
  }
}

然后编译此代码(我相信是内存文件系统 - 但我不确定)并执行.查看 ScriptRunner,我看到在默认的temp文件夹下创建了一个临时目录.例如,查看我的系统,我看到一堆 %TEMP%/scalascript* 文件夹.

This code is then compiled (I believe to a memory filesystem - but I'm not sure) and executed. Looking at ScriptRunner, I see that a temporary directory is created under the default temp folder. For instance looking at my system, I see a bunch of %TEMP%/scalascript* folders.

请注意,即使在解释器中,代码也不会被解释.见 Scala:有没有如果没有定义类,默认类是什么? 了解更多信息(它实际上正在被重写、编译和评估).

Note that even in the interpreter, the code is not interpreted. See Scala: Is there a default class if no class is defined? for more info (it's really being rewritten, compiled and evaluated).