Command Line Arguments in Scala
Our first program demonstrates how to handle command-line arguments in Scala. Here’s the full source code:
To experiment with command-line arguments, it’s best to compile the Scala code first:
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.