Main method in Scala

user2327621 picture user2327621 · May 1, 2014 · Viewed 64.7k times · Source

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?

Answer

Apoorv Verma picture Apoorv Verma · Dec 21, 2015

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.