« Return to Thread: main method in file with class and object?

Re: main method in file with class and object?

by Eric Willigers :: Rate this Message:

Reply to Author | View in Thread

John Tyler wrote:

> Hello, I'm trying to verify some behavior I've seen.  I defined a file
> MyApp.scala as such:
> class MyApp {
>   // blah
> }
>
> object MyApp {
>   def main(args: Array[String]) {
>     val app = new MyApp
>     // blah
>   }
> }
>
> I then compiled with "scalac MyApp.scala", but when I run with "scala
> MyApp" from the same directory I get:
> java.lang.NoSuchMethodException: MyApp.main([Ljava.lang.String ;)


You might choose to explicitly declare that def main returns type Unit

But the problem you are hitting is that you have both a class MyApp and
an object MyApp. main won't work in such cases. Rename the class MyApp
and you'll be fine.   You'll see that object MyApp compiles to
MyApp.class and MyApp$.class while class MyApp also compiles to
MyApp.class - a collision. Class MyApp dominates instead of there being
a merge (which might be hard with incremental compiling, separate
compiling, etc).

 « Return to Thread: main method in file with class and object?