To answer your question, have a look on the following :
I made a scala class, compiled and decompiled it, and what I got is interesting.
class MyScalaClass{
def main(args: Array[String]): Unit = {
println("Hello from main of class")
}
}
Compiled from "MyScalaClass.scala"
public class MyScalaClass {
public void main(java.lang.String[]);
public MyScalaClass();
}
So it means that when the scala class is converted to java class then the main method of the scala class which in turn being converted to the main method in java class is (not static)
.
And hence we would not be able to run the program because JVM is not able to find the starting point in the program.
But if the same code is done by using the ('object') keyword then:
Compiling the following:
object MyScalaClass{
def main(args: Array[String]): Unit = {
println("Hello from main of object")
}
}
Decompiling the following:
javap MyScalaClass$.class
Compiled from "MyScalaClass.scala"
public final class MyScalaClass$ {
public static final MyScalaClass$ MODULE$;
public static {};
public void main(java.lang.String[]);
}
Decompiling the following
javap MyScalaClass.class
Compiled from "MyScalaClass.scala"
public final class MyScalaClass {
public static void main(java.lang.String[]);
}
So here we got( public static void main in MyScalaClass.class) therefore the main method can be executed directly by the JVM here.
I hope you got your answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…