0

The contents of myfile.scala are as follows :

//  println("print this line")

object myObj  {
        def main(args: Array[String]): Unit = {
                println("Hello, world!")
        }
}

If I run : scala myfile.scala, it prints : Hello, world

If I uncomment the first println stmt, and run : scala myfile.scala, it only prints : print this line , and does not print hello-world stmt.

Why is this so? I find it very confusing. I tried to search the archives, but could not find any answers.

puhlen
  • 8,400
  • 1
  • 16
  • 31
user137392
  • 11
  • 3
  • 3
    This question has nothing to do with oo or functional programming – puhlen Feb 20 '17 at 02:27
  • It's a fair question but the title is completely unrelated. – pedrofurla Feb 20 '17 at 02:36
  • An easy way to accomplish this is to have myObj extend App. This will essentially treat the entire contents of the object as `main`. – WillD Feb 20 '17 at 03:00
  • You may reference the following questions to start an App. http://stackoverflow.com/questions/24437423/in-scala-should-i-use-the-app-trait and http://stackoverflow.com/questions/11667630/difference-between-using-app-trait-and-main-method-in-scala – Chen OT Feb 20 '17 at 06:54
  • Fair question, nothing in it to invite -1 – sujit Feb 23 '18 at 09:50

1 Answers1

4

When the scala command sees a top level statement (not in a class or object) in the file, it runs the file as a script, starting at the first line and moving down. You main method never gets called because you never call it, just define it. When your file doesn't contain any top level statements but it does contain a main object, it will run the main method as the entry point to the program.

puhlen
  • 8,400
  • 1
  • 16
  • 31