Main method in Scala

后端 未结 3 1900
春和景丽
春和景丽 2020-12-09 01:29

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

3条回答
  •  萌比男神i
    2020-12-09 02:00

    As Eugene said in a comment, there are no static methods in Scala. But watch this:

    $ cat Echo.scala
    object Echo {
      def main( args:Array[String] ):Unit = args foreach println
    }
    
    $ scalac Echo.scala
    
    $ javap Echo\$.class
    Compiled from "Echo.scala"
    public final class Echo$ {
      public static final Echo$ MODULE$;
      public static {};
      public void main(java.lang.String[]);
    }
    
    $ javap Echo.class
    Compiled from "Echo.scala"
    public final class Echo {
      public static void main(java.lang.String[]);
    }
    

    Note that the classfile for the Echo class (not Echo$, the object) does indeed have a public static void main method. Scala generates static methods for methods defined in objects for compatibility with Java.

    However, I consider creating a main method in a Scala program an anachronism. Use the App trait instead; it's cleaner:

    object Echo extends App {
      args foreach println
    }
    

提交回复
热议问题