scala object extends app 不打印任何东西

scala object extends app does not print anything

我正在学习 Scala,作为旅程的一部分,我遇到了两种不同的方式来编写你的 Scala class - 一种有 main 方法,另一种没有 main 方法,但通过扩展 App(早期 应用程序 由于并发问题已弃用

我正在通过 scala 可执行文件作为 scala <nameOfScript>.scala 在命令行中执行脚本。我 运行 Scala 2.11.7Windows.

使用 main 方法 运行ning scala script/class 时没有问题。

object ObjectWithMainMethod {
    def main(args:Array[String]) = {
            println("Object with a main() method executed..")
    }
}

它产生以下输出。

Object with a main() method executed..

但是,我没有得到对应的输出,它正在扩展 App 特征但没有 main 方法。

object AppWithoutMainMethod extends App {
    println("AppWithout main() method executed")
}

当我运行这个scala脚本时,它不打印任何东西。但是,当我通过 javap 实用程序查看已编译的 .class 文件时,我可以在其中看到 PSVM(public static void main() 方法)。

我错过了什么吗?对此的任何帮助将不胜感激。

如果你 运行 scala -help 你会看到这条评论:

A file argument will be run as a scala script unless it contains only self-contained compilation units (classes and objects) and exactly one runnable main method. In that case the file will be compiled and the main method invoked. This provides a bridge between scripts and standard scala source.

这完全解释了您所看到的内容 - scala 命令主要用于执行 "scripts" 或一系列表达式 - 以快速、交互式地评估代码片段。它只是 运行s "applications"(即具有 main 方法的对象)作为 "special case",因为用户会尝试以这种方式使用它是有意义的。所以:

  • 当你 运行 scala ObjectWithMainMethod.scala 时,主要方法被识别并且命令输入这个 "special case",弄清楚你可能想让它以这种方式工作
  • 当您 运行 scala AppwithoutMainMethod.scala 时,即使 App 有一个 main 方法,它也不会被识别为 "special case",而只是一个一系列表达式,因此不会调用 main 方法。

如果您将 类 编译成 .class 文件并通过 java -cp <classpath> <class-name> 命令编译 运行 它们,两者将产生相同的结果。

如果我 运行 没有 .scala 扩展名的文件,同样的事情会起作用。我不确定这背后的原因。

scala AppWithoutMainMethod

它产生以下输出

AppWithout main() method executed