scala 在scala中使用App trait和main方法的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11667630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between using App trait and main method in scala
提问by Ramesh
What is the difference between
之间有什么区别
object Application extends App {
println("Hello World")
}
and
和
object Application {
def main(args: Array[String]): Unit = {
println("Hello World");
}
}
采纳答案by Emil H
The App trait is a convenient way of creating an executable scala program. The difference to the main method altenative is (apart from the obvious syntactic differences) that the App trait uses the delayed initalization feature.
App trait 是一种创建可执行 Scala 程序的便捷方式。与 main 方法的不同之处在于(除了明显的语法差异)App trait 使用了延迟初始化功能。
From the release notes for 2.9 (see http://www.scala-lang.org/old/node/9483)
来自 2.9 的发行说明(参见http://www.scala-lang.org/old/node/9483)
Objects inheriting the App trait instead make use of Scala 2.9's delayed initialization feature to execute the whole body as part of an inherited main method.
Another new feature of the App scheme is that command line arguments are now accessible via the args value (which is inherited from trait App)
继承 App trait 的对象使用 Scala 2.9 的延迟初始化特性来执行整个主体,作为继承的 main 方法的一部分。
App 方案的另一个新特性是命令行参数现在可以通过 args 值访问(继承自 trait App)
回答by Taewon
These two cases is not same on the scala scripting.
这两种情况在 Scala 脚本上并不相同。
object extends Appwas not executed by "scala MyObject.scala" command,
but the object containing the mainmethod was executed by "scala MyObject.scala" command.
Which was described as scala looking for object with main method for scripting.
object extends App不是由“ scala MyObject.scala”命令执行,但包含主要方法的对象由“ scala MyObject.scala”命令执行。这被描述为 scala 用主要的脚本方法寻找对象。
When using REPL or scala workseet of Eclipse,
need to call MyObject.main(Array[String]())explicitly for both cases.
使用 Eclipse 的 REPL 或 scala workseet 时,MyObject.main(Array[String]())两种情况都需要显式调用。
This simple tip be helpful for beginner like me.
这个简单的技巧对像我这样的初学者很有帮助。
回答by a-herch
App trait is implemented using the [[DelayedInit]] functionality, which means that fields of the object will not have been initialized before the main method has been executed.
App trait 是使用 [[DelayedInit]] 功能实现的,这意味着在执行 main 方法之前,对象的字段不会被初始化。

