What really happens behind the Scala runtime/REPL when running a '.scala' program?

北慕城南 提交于 2020-01-01 04:03:08

问题


When I run something like the following from the command line, what really happens?

> scala hello.scala

Is there a hello.class generated, executed, and then discarded? Or does Scala behave somehow like an interpreter in this case? I am just thinking that, of course, I cannot do the same for Java:

> java hello.java

回答1:


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)

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()
      }
    }
  }
}

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.

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).



来源:https://stackoverflow.com/questions/7655165/what-really-happens-behind-the-scala-runtime-repl-when-running-a-scala-progra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!