Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

class - Main method in Scala

I wrote a Scala class and defined the main() method in it. It compiled, but when I ran it, I got NoSuchMethodError:main. In all the scala examples, I have seen, the main method is defined in an object. In Java we define the main method in a class. Is it possible to define main() in a Scala class or do we always need an object for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...