Difference between using App trait and main method in scala

后端 未结 3 920
清酒与你
清酒与你 2020-11-28 21:55

What is the difference between

object Application extends App {
   println(\"Hello World\")
}

and

object Application {
           


        
相关标签:
3条回答
  • 2020-11-28 22:37

    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.

    0 讨论(0)
  • 2020-11-28 22:41

    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)

    0 讨论(0)
  • 2020-11-28 22:44

    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.

    0 讨论(0)
提交回复
热议问题