Scala: Class, Object, APP in Eclipse Scala plug in
In Eclipse plugin, I could create scala Object, APP and class. But what's the difference among these 3. Basically, for objec开发者_C百科t, I implement def main(...), then I could run it. But in class, it seems it is similar to normal Java class, but what's the meaning scala APP, it creates a object which extends APP. What's this meant for?
In the JVM, the starting point of the application is a static method main(String[] args)
, in some class given to the JVM.
In scala there is no static methods, the equivalent is to put a method in an object (as opposed to class). Putting your main method in a class will not work, it is the same as not marking the method static in java.
App
is a helper that allows not to write the main method, and put the code directly in the object body.
object MyApp extends App {
doStuff
}
does the same thing as
object MyApp {
def main(args: Array[String]) {doStuff}
}
(arguments can be used in doStuff under the name args
)
Scala has no static methods, so public static void main
is not available for classes.
Objects are single entries that better fits the "common to every object of a class" scope. So, oversimplifying things, you can think of Object as a Singleton which "acts as an only-static container" (quote from Scala for Java Refugees). If you think about it, that's the perfect place for a main method, and that's why they are declared there.
The App trait just explores the fact that instructions written inside the body of an Object are executed as part of its initialization. It couples this standard behaviour with some delayed initialization tricks to use the body of an object as the main method. So, you can think about it as a short alternative syntax to create a application entry point. It replaced the naive Application trait that had a lot of shortcomings.
Which one of the two to use is really a matter of taste, but I tend to stick with the more familiar main method syntax.
Cheers,
精彩评论