启动一个Scala项目,有两种方法:
- 使用main:
object Application extends App {
println("Hello World")
}
- 利用App特质:
object Application {
def main(args: Array[String]): Unit = {
println("Hello World");
}
}
那么,这两种启动项目的方式有什么不同呢?
App是scala语言内置的一个特质,使用它,则把对应object内部的整体作为scala main的一部分,有延迟启动的特性。同时,命令行参数args也作为App特质的一部分,可以被开发者直接使用。而main函数则是scala的默认启动方式。
其实,我们可以在scala的官方文档中找到上述内容:
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特质时,可能导致extends App的object内部有错误时整个项目启动失败。所以,用main的方式启动项目更加稳妥。