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");
    }
}
Ramesh
  • 2,295
  • 5
  • 35
  • 64
  • 1
    possible duplicate of [In Scala; should I use the App trait?](http://stackoverflow.com/questions/24437423/in-scala-should-i-use-the-app-trait) – mmmmmm Apr 21 '15 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 '18 at 06:06

3 Answers3

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)

Community
  • 1
  • 1
Emil L
  • 20,219
  • 3
  • 44
  • 65
  • 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? – Richard Sitze Jul 28 '12 at 09: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 '12 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.

Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
Taewon
  • 133
  • 2
  • 2
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.

a-herch
  • 137
  • 1
  • 4
  • 12