98

What is the difference between

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

and

object Application {
    def main(args: Array[String]): Unit = {
        println("Hello World");
    }
}
2
  • 1
    possible duplicate of In Scala; should I use the App trait?
    – mmmmmm
    Apr 21, 2015 at 10:05
  • 2
    In the case of Apache Spark jobs, documentation states "that applications should define a main() method instead of extending scala.App. Subclasses of scala.App may not work correctly."
    – leo9r
    May 16, 2018 at 6:06

3 Answers 3

69

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)

2
  • 1
    Am I correct in my understanding that without the benefit of the App trait, this (Application) object doesn't act like any other scala object - in that the entry point is the main method and the body isn't executed as expected. Is it executed at all at some point after entry to main? Jul 28, 2012 at 9:38
  • @RichardSitze There is a main method in the App trait witch get's mixed in to your Application object. There is no magic going on beyond the fact that the delayed initialization is what executes the body of your Application object.
    – Emil L
    Jul 28, 2012 at 18:06
5

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.