Hello World by Defining a 'main' Method

Download scala eBook


Place this code in a file named HelloWorld.scala:

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

Live demo

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!


Contributors: 17
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook