【问题标题】:How to run scala file from command line?如何从命令行运行scala文件?
【发布时间】:2020-06-05 21:13:40
【问题描述】:

scala 是否支持scala run xxx.scala? go语言支持像这样运行

go my.go

和python支持

python my.py

不过好像

scala xxx.scala

只是语法检查,没有观察到输出或运行行为。那么有没有办法直接运行一个scala文件呢?

【问题讨论】:

标签: scala file command-line-interface read-eval-print-loop scala-repl


【解决方案1】:

scala 跑步者的目标可以通过-howtorun 明确指定

If the runner does not correctly guess how to run the target:

 -howtorun    what to run <script|object|jar|guess> (default: guess)

例如,假设我们有一个胖罐子,那么我们可以用它来运行它

scala -howtorun:jar myapp.jar

默认情况下,scala runner 尝试猜测并将命名的目标运行为

  • 带有 main 方法的编译类
  • 带有 Main-Class 清单头的 jar 文件
  • 要编译和运行的 Scala 源文件

例如,给定以下Hello.scala源文件

// source file Hello.scala
object Hello {
  def main(args: Array[String]): Unit = {
    println("Hello World!")
  }
}

然后执行scala Hello.scala 应该在上面的第三个要点输出Hello World!

也可以考虑Your First Lines of Scala

【讨论】:

    【解决方案2】:

    看起来很简单。但是你必须使用 println 来打印一些东西。

    ➜  ~ cat hello.scala
    println("hello, world")
    ➜  ~ scala hello.scala
    hello, world
    ➜  ~ scala -Vprint:parser hello.scala
    [[syntax trees at end of                    parser]] // hello.scala
    package <empty> {
      object Main extends scala.AnyRef {
        def <init>() = {
          super.<init>();
          ()
        };
        def main(args: Array[String]): scala.Unit = {
          final class $anon extends scala.AnyRef {
            def <init>() = {
              super.<init>();
              ()
            };
            println("hello, world")
          };
          new $anon()
        }
      }
    }
    
    hello, world
    ➜  ~ 
    

    或者有几种方法可以向 REPL 提供行,它会为您打印结果。

    ➜  ~ cat calc.scala
    2 + 2
    ➜  ~ scala < calc.scala
    Welcome to Scala 2.13.1 (OpenJDK 64-Bit Server VM, Java 11.0.3).
    Type in expressions for evaluation. Or try :help.
    
    scala> 2 + 2
    res0: Int = 4
    
    scala> :quit
    ➜  ~ 
    

    另请参阅 -i-I-e 以及 :load:paste 命令。

    如另一个答案所示,它还将在对象中查找 Java 样式的 main 方法。这就是你通常编译程序入口点的方式。

    【讨论】:

      【解决方案3】:

      对于这种情况,我绝对推荐ammoninte。它是独立的工具,但具有更多功能并且运行良好。

      更多关于http://ammonite.io/

      【讨论】:

        【解决方案4】:

        在运行 scala 源代码之前,您需要使用编译 scala 代码 scalac filename.scala 命令。 要执行编译的 scala 文件,您需要键入以下命令: scala filename

        【讨论】:

        • 虽然这是真的,但有一个标志可以将所有内容传递给解释器。您还可以在脚本的请求处使用魔法#! /usr/bin/env scala 编写一个 scala 脚本。
        猜你喜欢
        • 1970-01-01
        • 2015-08-13
        • 2016-02-05
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 2017-10-01
        相关资源
        最近更新 更多