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.

5
  • 3
    This question has nothing to do with oo or functional programming Commented Feb 20, 2017 at 2:27
  • It's a fair question but the title is completely unrelated. Commented Feb 20, 2017 at 2: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. Commented Feb 20, 2017 at 3:00
  • You may reference the following questions to start an App. stackoverflow.com/questions/24437423/… and stackoverflow.com/questions/11667630/… Commented Feb 20, 2017 at 6:54
  • Fair question, nothing in it to invite -1 Commented Feb 23, 2018 at 9:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.