×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Command Line Arguments in Scala

By IncludeHelp Last updated : November 16, 2024

Scala provides its user an option to input values to a function.

Arguments: Arguments are the values that are provided to the function and will be used in the function to perform tasks.

Command-line Arguments

Command-Line Arguments in Scala are the arguments that are provided to the main function of Scala. These can be used in the program and are provided by the user while compiling the code after calling the name of the program.

Syntax

Main method: 
	def main(args: Array[String])
Command line: 
	scala program_name argument1 argument2 ...

The arguments will be passed on to the function as an array of strings name to access it is args[].

Example 1: Illustrate the working of command-line arguments

object myObject {
    def main(args: Array[String]): Unit = {
        println("Command Line arguments: ")
        for(i <- 0 to args.length-1)
            println( "args(" + i + ") : " + args(i) )
    }
}

Output

Command Line: scala programming language

Output: 
Command Line arguments: 
args(0) : scala
args(1) : programming
args(2) : language

Explanation

In the above program, we have simply passed a line as a command-line argument. Which we have accessed using the for loop in Scala for printing array.

Example 2: To get command-line arguments and perform operations

object myObject {

  def main(args: Array[String]): Unit = {
    if (args.length < 2) {
      println("Error: Please provide two integer arguments.")
      return
    }

    try {
      val value1 = args(0).toInt
      val value2 = args(1).toInt

      println("value 1 = " + value1)
      println("value 2 = " + value2)

      val sum = value1 + value2
      println("sum = " + sum)

    } catch {
      case e: NumberFormatException =>
        println("Error: Both arguments must be valid integers.")
    }
  }

}

Output

Command Line: 34 123

Output: 
value 1 = 34
value 2 = 123
sum = 157

Explanation

Here, we have taken to integers as command-line arguments. These command-line arguments are taken as strings which we have converted to int using the toInt method. We have printed the values as integers and then printed sum too.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.