Difference between using App trait and main method in scala
ScalaScala Problem Overview
What is the difference between
object Application extends App {
println("Hello World")
}
and
object Application {
def main(args: Array[String]): Unit = {
println("Hello World");
}
}
Scala Solutions
Solution 1 - Scala
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.
From the release notes for 2.9 (see 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)
Solution 2 - Scala
These two cases is not same on the scala scripting.
object extends App
was not executed by "scala MyObject.scala
" command,
but the object containing the main method was executed by "scala MyObject.scala
" command.
Which was described as scala looking for object with main method for scripting.
When using REPL or scala workseet of Eclipse,
need to call MyObject.main(Array[String]())
explicitly for both cases.
This simple tip be helpful for beginner like me.
Solution 3 - Scala
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.