开发者

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

开发者 https://www.devze.com 2023-04-11 07:01 出处:网络
When I run something like the following from the command line, what really happens? > scala hello.scala

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号