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

前端 未结 1 1277
栀梦
栀梦 2021-02-12 14:35

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

> scala hello.scala

Is there a hello.class generated, e

相关标签:
1条回答
  • 2021-02-12 14:57

    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 讨论(0)
提交回复
热议问题