Command-Line Interface (CLI) applications offer a powerful and efficient way to interact with software, allowing users to execute commands and automate tasks directly from their terminal. Kotlin, with its concise syntax, excellent tooling, and interoperability with Java, is an ideal language for building robust CLI applications. This article will guide you through creating a simple yet effective CLI application using Kotlin.
What is a CLI Application?
A Command-Line Interface (CLI) application is a program that interacts with users through text-based commands. Instead of using a graphical interface, users type commands into a terminal or console to execute tasks.
Why Kotlin for CLI Applications?
- Concise Syntax: Kotlin’s expressive and concise syntax reduces boilerplate code, making development faster.
- Interoperability: Kotlin seamlessly integrates with existing Java libraries and frameworks, giving you access to a wide range of tools.
- Multiplatform: Kotlin Multiplatform allows you to target different platforms, including JVM, Native, and JavaScript, from a single codebase.
- Coroutines: Kotlin’s coroutines simplify asynchronous programming, enabling you to write non-blocking code.
Setting Up a Kotlin CLI Project
Let’s start by setting up a new Kotlin project for our CLI application.
Step 1: Using IntelliJ IDEA
- Open IntelliJ IDEA.
- Click on “Create New Project.”
- Select “Kotlin” in the left pane.
- Choose “Kotlin/JVM” and click “Next.”
- Enter your project name (e.g., “kotlin-cli”) and location.
- Click “Create.”
Step 2: Project Structure
The project structure will look like this:
kotlin-cli/
├── src/
│ └── main/
│ └── kotlin/
│ └── Main.kt
└── build.gradle.kts
Step 3: Configure build.gradle.kts
Open build.gradle.kts
and add the necessary plugins and dependencies. Here’s a basic configuration:
plugins {
kotlin("jvm") version "1.9.21"
application
}
group = "com.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-cli:0.3.6")
testImplementation(kotlin("test"))
}
application {
mainClass.set("MainKt")
}
tasks.test {
useJUnitPlatform()
}
Key components in this build configuration:
- kotlin(“jvm”): Configures the Kotlin JVM plugin.
- application: Enables the application plugin, allowing you to create executable JAR files.
- kotlinx-cli: A Kotlin library for parsing command-line arguments.
- mainClass: Specifies the main class of your application.
Step 4: Add Kotlinx CLI Dependency
We will be using `kotlinx-cli` library, add it in the gradle.
implementation("org.jetbrains.kotlinx:kotlinx-cli:0.3.6")
Building a Simple CLI Application
Let’s create a basic CLI application that accepts a name as an argument and prints a greeting message.
Step 1: Create the Main Class
Open src/main/kotlin/Main.kt
and add the following code:
import kotlinx.cli.*
fun main(args: Array) {
val parser = ArgParser("GreetingApp")
val name by parser.option(ArgType.String, shortName = "n", longName = "name", description = "Name to greet").default("World")
parser.parse(args)
println("Hello, $name!")
}
In this code:
- ArgParser(“GreetingApp”): Creates a new argument parser for the application named “GreetingApp”.
- val name by parser.option(…): Defines an option named “name” that accepts a string value. It uses a short name “n” and a long name “name”. If no name is provided, it defaults to “World”.
- parser.parse(args): Parses the command-line arguments provided to the application.
- println(“Hello, $name!”): Prints a greeting message using the provided or default name.
Adding More Features
Let’s enhance our CLI application by adding more features.
Adding More Options
We can add more options to the CLI application, such as an option to specify the greeting message.
import kotlinx.cli.*
fun main(args: Array) {
val parser = ArgParser("GreetingApp")
val name by parser.option(ArgType.String, shortName = "n", longName = "name", description = "Name to greet").default("World")
val greeting by parser.option(ArgType.String, shortName = "g", longName = "greeting", description = "Greeting message").default("Hello")
parser.parse(args)
println("$greeting, $name!")
}
In this enhanced version, we’ve added a new option called “greeting” with a default value of “Hello”.
Adding Subcommands
Subcommands can help organize different functionalities of the application into logical groups.
import kotlinx.cli.*
sealed class Command : Subcommand(null, "") {
class Greet : Subcommand("greet", "Greets the user") {
val name by option(ArgType.String, shortName = "n", longName = "name", description = "Name to greet").default("World")
val greeting by option(ArgType.String, shortName = "g", longName = "greeting", description = "Greeting message").default("Hello")
override fun execute() {
println("$greeting, $name!")
}
}
class Goodbye : Subcommand("goodbye", "Bids farewell to the user") {
val name by option(ArgType.String, shortName = "n", longName = "name", description = "Name to say goodbye to").default("World")
override fun execute() {
println("Goodbye, $name!")
}
}
}
fun main(args: Array) {
val parser = ArgParser("GreetingApp")
parser.subcommands(Command.Greet(), Command.Goodbye())
parser.parse(args)
}
This code defines two subcommands, “greet” and “goodbye,” each with its own set of options.
Building and Running the CLI Application
To build and run the CLI application, follow these steps:
Step 1: Build the Application
- Open the Gradle tool window in IntelliJ IDEA (View > Tool Windows > Gradle).
- Navigate to “Tasks” > “application” and double-click “jar”.
- This will generate a JAR file in the
build/libs
directory.
Step 2: Run the Application
Open your terminal and navigate to the build/libs
directory. Run the application using the following command:
java -jar kotlin-cli-1.0-SNAPSHOT.jar --name John
Output:
Hello, John!
To use the subcommands, run the application with the appropriate subcommand and options:
java -jar kotlin-cli-1.0-SNAPSHOT.jar greet --name Jane --greeting Hi
Output:
Hi, Jane!
Conclusion
Building a CLI application with Kotlin is straightforward and efficient, thanks to its concise syntax, powerful libraries, and seamless Java interoperability. This article covered setting up a Kotlin project, adding dependencies, building a simple CLI application, and adding more features such as options and subcommands. With these fundamentals, you can create robust and user-friendly CLI applications for various purposes.