How to read Scala command line arguments

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

Solution

Note: I need to update/re-write this article, but the short story is that if you create a Scala object like this:

object Foo extends App { ...

you can access your Scala command-line arguments using the args array, which is made available to you implicitly when you extend App. As an example, your code will look like this:

object Foo extends App {
    if (args.length == 0) {
        println("dude, i need at least one parameter")
    }
    val filename = args(0)
    ...
}

You’ll access the args array like that whether you’re writing a Scala shell script or a full-blown Scala application.

And now for the rest of the article, which is all about Scala shell scripts (and not written very well) ...

Command line args with Scala shell scripts

If your Scala shell script is 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.

How to read 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; 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.