Questions And Answers

More Tutorials

Scala Tutorial


Hello World by Defining a 'main' Method

Place this code in a file named HelloWorld.scala:

object Hello {
 def main(args: Array[String]): Unit = {
 println("Hello World!")

To compile it to bytecode that is executable by the JVM:

$ scalac HelloWorld.scala

To run it:

$ scala Hello

When the Scala runtime loads the program, it looks for an object named Hello with a main method. The main method is the program entry point and is executed.

Note that, unlike Java, Scala has no requirement of naming objects or classes after the file they're in. Instead, the parameter Hello passed in the command scala Hello refers to the object to look for that contains the main method to be executed. It is perfectly possible to have multiple objects with main methods in the same .scala file.

The args array will contain the command-line arguments given to the program, if any. For instance, we can modify the program like this:

object HelloWorld {
 def main(args: Array[String]): Unit = {
 println("Hello World!")
 for {
 arg <- args
 } println(s"Arg=$arg")

Compile it:

$ scalac HelloWorld.scala

And then execute it:

$ scala HelloWorld 1 2 3
Hello World!

Hello World by extending App

object HelloWorld extends App {
 println("Hello, world!")


In this page (written and validated by ) you learned about Scala Tutorial . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Annotations.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.