Reputation: 77
How does a main method gets called in scala ? Why does a main method gets called in when it is written only in object but not in class ?
Upvotes: 2
Views: 1705
Reputation: 503
It is because in scala the only way to define a method static is object class. And also it is necessary only one instance of main class is created , not multiple instances. That's why it is object class
Upvotes: 0
Reputation: 8529
The main method must be a static method. In Scala to create a static method you put it in an object. Methods in a class are not static.
In the scala language they decided to separate class, which hold only instance behavior and state, and object which hold static behavior and state. This is different from java where classes hold both instance and static members where something is made static using the static
keyword.
Upvotes: 3
Reputation: 44918
Because the specification says so:
A program is a top-level object that has a member method main of type
(Array[String])Unit
. Programs can be executed from a command shell. The program's command arguments are passed to the main method as a parameter of typeArray[String]
.The main method of a program can be directly defined in the object, or it can be inherited.
It speaks only about top-level objects, not classes. If you define a main
method in a class, then it will be just an ordinary method that you can invoke on the instances of this class. Unless you define a top-level object that inherits the main
from this class / trait, this method called main
will not be treated as an entry point of the application.
Upvotes: 5