Home »
Scala programs
Command Line Arguments in Scala
Here, we will learn about command-line arguments in Scala. Command-line arguments are inputs to the program from the command-line.
Submitted by Shivang Yadav, on December 13, 2020
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 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[].
Program 1: Program to illustrate the working of command-line arguments
object myObject {
def main(args: Array[String]) {
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.
Program 2: To get command-line arguments and perform operations
object myObject {
def main(args: Array[String]) {
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)
}
}
object myObject {
def main(args: Array[String]) {
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)
}
}
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.