运行“.scala"程序时,Scala 运行时/REPL 背后到底发生了什么? [英] What really happens behind the Scala runtime/REPL when running a '.scala' program?

查看:44
本文介绍了运行“.scala"程序时,Scala 运行时/REPL 背后到底发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从命令行运行类似以下内容时,到底发生了什么?

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

> scala hello.scala

是否有 hello.class 生成、执行、然后丢弃?或者在这种情况下 Scala 的行为是否像解释器?我只是在想,当然,我不能对 Java 做同样的事情:

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

推荐答案

是的,有一个 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).

这篇关于运行“.scala"程序时,Scala 运行时/REPL 背后到底发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆