Reputation: 1017
I am learning Scala and as part of the journey I had come across two different ways to write your scala class - one with a main method and other without the main method but by extending App (earlier Application is deprecated due to concurrency issues).
I am executing the scripts in Command Line via scala
executable as scala <nameOfScript>.scala
. I run Scala 2.11.7 in Windows.
I have no issues when running a scala script/class with a main method.
object ObjectWithMainMethod {
def main(args:Array[String]) = {
println("Object with a main() method executed..")
}
}
It produces the following output.
Object with a main() method executed..
But, I don't get the output with its counterpart, which is extending App trait but without the main method.
object AppWithoutMainMethod extends App {
println("AppWithout main() method executed")
}
When I run this scala script, it does not print anything. However, when I looked at the complied .class files via javap utility, I could see the PSVM (public static void main() method) inside.
Am I missing something? Any help on this will be highly appreciated.
Upvotes: 0
Views: 1406
Reputation: 1017
The same thing works if I run the file without the .scala
extension. I am not sure the reason behind this.
scala AppWithoutMainMethod
It produces the following output
AppWithout main() method executed
Upvotes: -1
Reputation: 37832
If you run scala -help
you'll see this comment:
A file argument will be run as a scala script unless it contains only self-contained compilation units (classes and objects) and exactly one runnable main method. In that case the file will be compiled and the main method invoked. This provides a bridge between scripts and standard scala source.
This explains exactly what you're seeing - the scala
command is primarily meant to execute "scripts", or a series of expressions - for quick, interactive evaluation of code snippets. It only runs "applications" (i.e. objects with main method) as a "special case", because it makes sense users will try to use it this way. So:
scala ObjectWithMainMethod.scala
, the main method is identified and the command enters this "special case", figuring out that you probably meant for it to work that wayscala AppwithoutMainMethod.scala
, even though App
has a main
method, this isn't identified as the "special case" but just as a series of expressions, so the main method isn't invoked. If you compile your classes into .class
files and run them via java -cp <classpath> <class-name>
command, the two will produce identical results.
Upvotes: 3