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

发布于 2024-12-07 23:43:32 字数 217 浏览 4 评论 0原文

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

> scala hello.scala

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

> java hello.java

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

つ低調成傷 2024-12-14 23:43:32

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

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

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

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%/scalascript* 文件夹。

请注意,即使在解释器中,代码也不会被解释。请参阅 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)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文