Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Command Line Argument in Scala

In Scala, just like in many programming languages, you can pass command line arguments to your program. These arguments are captured in the args array, which is passed to the main method of your program.

Here's a basic introduction to using command line arguments in Scala:

1. Define a Main Method:

The entry point of a Scala application is the main method. The main method takes an array of strings (Array[String]) as a parameter, which represents the command line arguments.

object MainApp {
  def main(args: Array[String]): Unit = {
    println("Command line arguments are:")
    args.foreach(println)
  }
}

2. Compile and Run:

Compile the program using the Scala compiler:

scalac MainApp.scala

Now, run the program using the scala command, passing some arguments:

scala MainApp arg1 arg2 arg3

This will output:

Command line arguments are:
arg1
arg2
arg3

3. Accessing Specific Arguments:

You can access specific arguments using their index. For example, args(0) refers to the first argument:

object MainApp {
  def main(args: Array[String]): Unit = {
    if (args.length > 0) {
      println(s"First argument is: ${args(0)}")
    } else {
      println("No arguments provided.")
    }
  }
}

4. Handling No Arguments:

It's good practice to handle cases where no arguments are provided:

object MainApp {
  def main(args: Array[String]): Unit = {
    if (args.isEmpty) {
      println("Please provide some arguments.")
    } else {
      println("Command line arguments are:")
      args.foreach(println)
    }
  }
}

5. Other Ways to Process Arguments:

Scala's rich collection library means you can use all the typical operations (like map, filter, etc.) on the args array. For instance, if you want to transform all the arguments to uppercase:

args.map(_.toUpperCase).foreach(println)

6. Advanced Argument Parsing:

For more advanced command line argument parsing (e.g., named arguments, default values), you might want to use a library like scopt. This library lets you define option parsers in a concise and idiomatic manner.

In conclusion, accessing command line arguments in Scala is straightforward using the args array in the main method. For complex use cases, consider using specialized libraries.

  1. Parsing command-line arguments in Scala:

    • Description: Command-line arguments are parameters passed to a Scala program when it is executed.
    • Code Example:
      object CommandLineApp {
        def main(args: Array[String]): Unit = {
          // Access and process command-line arguments here
        }
      }
      
  2. Accessing arguments in Scala main method:

    • Description: The main method in Scala takes an array of strings (args) as its parameter, representing the command-line arguments.
    • Code Example:
      object CommandLineApp {
        def main(args: Array[String]): Unit = {
          // Access and process command-line arguments from 'args'
          println("Arguments: " + args.mkString(", "))
        }
      }
      
  3. Using args array in Scala:

    • Description: The args array contains the command-line arguments passed to the Scala program.
    • Code Example:
      object CommandLineApp {
        def main(args: Array[String]): Unit = {
          // Access and process command-line arguments
          if (args.length > 0) {
            println("First argument: " + args(0))
          }
        }
      }
      
  4. Passing arguments to Scala scripts:

    • Description: Scala scripts can receive command-line arguments similarly to compiled programs.
    • Code Example:
      // script.scala
      val arg1 = args(0)
      val arg2 = args(1)
      
      println(s"Argument 1: $arg1, Argument 2: $arg2")
      
  5. Custom argument parsing in Scala:

    • Description: For specific or complex parsing needs, custom logic can be implemented to process command-line arguments.
    • Code Example:
      object CustomArgParsing {
        def main(args: Array[String]): Unit = {
          // Custom argument parsing logic
          val customArg = args.find(_.startsWith("--custom=")).map(_.substring("--custom=".length))
      
          customArg.foreach { value =>
            println(s"Custom Argument: $value")
          }
        }
      }
      
  6. Scala scopt library for command-line parsing:

    • Description: The scopt library simplifies command-line parsing in Scala by providing a convenient DSL for defining options and arguments.
    • Code Example:
      import scopt._
      
      case class Config(foo: Int = -1, bar: String = "", baz: Boolean = false)
      
      object ScoptExample {
        def main(args: Array[String]): Unit = {
          val parser = new scopt.OptionParser[Config]("ScoptExample") {
            head("ScoptExample", "1.0")
      
            opt[Int]('f', "foo").action((x, c) => c.copy(foo = x)).text("foo is an integer property")
            opt[String]('b', "bar").action((x, c) => c.copy(bar = x)).text("bar is a string property")
            opt[Boolean]('z', "baz").action((x, c) => c.copy(baz = x)).text("baz is a boolean property")
      
            help("help").text("prints this usage text")
      
            arg[String]("arg1").action((x, c) => c.copy(bar = x)).text("arg1 is a required string argument")
          }
      
          parser.parse(args, Config()) match {
            case Some(config) =>
              // Process the configuration
              println(config)
            case None =>
            // Arguments are incorrect, error message will be displayed
          }
        }
      }