Command Line Arguments in Scala

Our first program demonstrates how to handle command-line arguments in Scala. Here’s the full source code:

import scala.jdk.CollectionConverters._

object CommandLineArguments {
  def main(args: Array[String]): Unit = {
    // `args` provides access to raw command-line arguments.
    // Note that unlike in some languages, the first element
    // of `args` is the first argument, not the program name.
    val argsWithProg = scala.util.Properties.javaRuntimeName +: args
    val argsWithoutProg = args

    // You can get individual args with normal indexing.
    val arg = if (args.length > 2) args(2) else ""

    println(argsWithProg.mkString(", "))
    println(argsWithoutProg.mkString(", "))
    println(arg)
  }
}

To experiment with command-line arguments, it’s best to compile the Scala code first:

$ scalac CommandLineArguments.scala
$ scala CommandLineArguments a b c d
OpenJDK 64-Bit Server VM, a, b, c, d
a, b, c, d
c

In Scala, the args parameter in the main method directly contains the command-line arguments, without including the program name. If you need the program name (or in this case, the Java runtime name), you can access it using scala.util.Properties.javaRuntimeName.

The mkString method is used to join the elements of the array into a single string for printing.

Note that accessing an array element that doesn’t exist will throw an ArrayIndexOutOfBoundsException. In this example, we’ve added a check to avoid this when accessing the third argument.

Next, we’ll look at more advanced command-line processing with configuration libraries in Scala.