Building a CLI Application in Scala
In this lesson, you will learn how to build a Command Line Interface (CLI) application using Scala. CLI applications are programs that run in a terminal and interact with users through text input and output.
CLI tools are widely used for automation, scripting, DevOps tasks, data processing, and developer utilities.
What Is a CLI Application?
A CLI application:
- Runs from the command line or terminal
- Accepts input through arguments or standard input
- Produces output as text
Examples include tools like git, docker,
and many system utilities.
Why Build CLI Tools in Scala?
Scala is an excellent choice for CLI tools because:
- It runs on the JVM and works across platforms
- Strong typing reduces runtime errors
- Easy integration with Java libraries
- Supports both functional and object-oriented styles
Basic Scala CLI Program
The simplest Scala CLI program prints output to the console.
object HelloCLI {
def main(args: Array[String]): Unit = {
println("Hello from Scala CLI!")
}
}
When executed, this program prints a message to the terminal.
Understanding the main Method
Every Scala CLI application starts execution from the
main method.
argsstores command-line argumentsArray[String]represents input valuesprintlnoutputs text
Reading Command-Line Arguments
You can pass arguments when running a Scala program.
object ArgsExample {
def main(args: Array[String]): Unit = {
println("Arguments:")
args.foreach(println)
}
}
If you run:
scala ArgsExample.scala one two three
Each argument will be printed on a new line.
Handling Missing Arguments
CLI tools must handle incorrect or missing input gracefully.
object SafeArgs {
def main(args: Array[String]): Unit = {
if (args.isEmpty) {
println("Please provide at least one argument.")
} else {
println(s"Hello, ${args(0)}")
}
}
}
This avoids runtime errors and improves user experience.
Reading User Input from Terminal
Scala can read input directly from the terminal using
scala.io.StdIn.
import scala.io.StdIn
object InputExample {
def main(args: Array[String]): Unit = {
print("Enter your name: ")
val name = StdIn.readLine()
println(s"Welcome, $name!")
}
}
This allows interactive CLI programs.
Building a Simple CLI Tool
Below is a simple CLI calculator that adds two numbers.
object CalculatorCLI {
def main(args: Array[String]): Unit = {
if (args.length != 2) {
println("Usage: calculator ")
} else {
val a = args(0).toInt
val b = args(1).toInt
println(s"Sum: ${a + b}")
}
}
}
This example demonstrates argument parsing and validation.
Using SBT to Run CLI Apps
You can run Scala CLI programs using SBT:
sbt run
SBT handles compilation and execution automatically.
Real-World Use Cases
Scala CLI tools are commonly used for:
- Automation scripts
- Build and deployment tools
- Data processing pipelines
- Developer utilities
📝 Practice Exercises
Exercise 1
Create a CLI program that prints all command-line arguments.
Exercise 2
Write a CLI program that asks the user for two numbers and prints their product.
Exercise 3
Add input validation to prevent invalid numbers.
✅ Practice Answers
Answer 1
args.foreach(println)
Answer 2
val x = StdIn.readInt()
val y = StdIn.readInt()
println(x * y)
Answer 3
try {
val n = args(0).toInt
println(n)
} catch {
case _: NumberFormatException =>
println("Invalid number")
}
What’s Next?
In the next lesson, you will learn about Logging in Scala, which is essential for monitoring and debugging real-world applications.