How to launch a Scala application with an object construct

  • Post category:Scala
  • Reading time:4 mins read

Problem

You want to start a Scala application with a main method, or provide the entry point for a script.

Solution

There are two ways to create a launching point for your application:

  1. Create an object that extends the App trait.
  2. Create an object with a properly defined main method.

Create an object that extends the App trait

For the first solution, define an object that extends the App trait. Using this approach, the following code creates a simple but complete Scala application:

object Hello extends App {
       println("Hello, world")
}

The code in the body of the object is automatically run, just as if it were inside a main method. Just save that code to a file named Hello.scala, compile it with scalac, and then run it with scala, like this:

$ scalac Hello.scala
$ scala Hello

When using this approach, any command-line arguments to your application are implicitly available through an args object, which is inherited from the App trait. The args object is an instance of Array[String], just as if you had declared a main method yourself. The following code demonstrates how to use the args object:

object Hello extends App {
     if (args.length < 1)
     println("No input arguments provided.")
}else{
     println(s"Hello, ${args(0)}")
}

After it’s been compiled, this program yields the following results:

$ scala Hello
No input arguments provided.
$ scala Hello Prakash
Hello, Prakash

Create an object with a properly defined main method

The second approach to launching an application is to manually implement a main method with the correct signature in an object, in a manner similar to Java:

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

NOTE:

Note that in both cases, Scala applications are launched from an object, not a class.

The Scala doc for the App trait currently includes two caveats:

It should be noted that this trait is implemented using the DelayedInit functionality, which means that fields of the object will not have been initialized before the main method has been executed.

It should also be noted that the main method will not normally need to be overridden: the purpose is to turn the whole class body into the “main method.” You should only choose to override it if you know what you are doing.