Reading Scala command line arguments

Scala command line FAQ: How do I read command line arguments (args) in a Scala shell script?

If your Scala shell script is very short, and you're not using an object or class declaration -- i.e., you have no main method -- you can access the script's command line arguments through the default args array, which is made available to you by Scala.

For instance, you can create a one-line Scala script named hello.scala like this:

println("Hello, " + args(0))

and then run the script like this:

scala hello.scala Al

and your output will look like this:

Hello, Al

As you can see, the command line arguments are accessed in Scala's array syntax, so the elements are args(0), args(1), etc.

Command line arguments with a Scala object

If you're using a Scala object in your shell script, you can still access the command line arguments using the args array, but in this case you just name the array args by convention:

object Foo {
  def main(args: Array[String]) = {
    println("Hello, " + args(0))
  }
}

You don't have to name the array "args", and in fact, you can name it whatever you'd like.

Looping through the Scala args array

As a reminder to myself more than anything else, if you want to loop through the Scala args array, there are several ways to do this, including these examples:

args.foreach(arg => println(arg))

// shorter
args.foreach(println(_))

// even shorter - if function literal consists of one
// statement that takes a single argument, you can do this:
args.foreach(println)

Scala shell script

As a final note, if you want to wrap your Scala script in a Unix/Linux shell script so you can easily execute it from the command line, take a look at my Scala shell script wrapper example. It shows the proper syntax for creating a "hello.sh" shell script that you can execute just like any other (normal) shell script.

I hope these tips on accessing command line arguments in your Scala scripts has been helpful.

Post new comment

The content of this field is kept private and will not be shown publicly.