Command-line arguments
suggest changeCommand-line arguments allow users to pass flags, configurations, and input targets to a Kotlin program upon launch. Kotlin supports standard JVM Array<String> main arguments as well as modern, type-safe CLI parsing libraries like Clikt and kotlinx-cli.
The main Function and args
In Kotlin, command-line arguments are received by the entry point function:
// 1. Classic entry point with arguments array
fun main(args: Array<String>) {
println("Received ${args.size} argument(s):")
for ((index, arg) in args.withIndex()) {
println(" [$index] = $arg")
}
}
Note: Since Kotlin 1.3,
fun main()without arguments is allowed for programs that do not consume CLI parameters. When parameters are needed,args: Array<String>is required.
Running from Command Line
# Compile to a standalone executable JAR
kotlinc Main.kt -include-runtime -d app.jar
# Run and pass arguments
java -jar app.jar --host localhost --port 8080 filename.txt
Manual Argument Parsing
For simple CLI scripts without third-party dependencies, Kotlin's collection functions make lightweight manual parsing straightforward:
import kotlin.system.exitProcess
fun main(args: Array<String>) {
if (args.isEmpty() || "--help" in args || "-h" in args) {
println("""
Usage: myapp [OPTIONS] <input-file>
Options:
-h, --help Show this help message
-v, --verbose Enable verbose diagnostic logging
--port=<int> Port number (default: 8080)
""".trimIndent())
exitProcess(0)
}
// Boolean flags
val verbose = "-v" in args || "--verbose" in args
// Key-value option parsing (--port=9000 or --port 9000)
val portOption = args.firstOrNull { it.startsWith("--port=") }?.substringAfter("--port=")
?: run {
val portIndex = args.indexOf("--port")
if (portIndex != -1 && portIndex + 1 < args.size) args[portIndex + 1] else null
}
val port = portOption?.toIntOrNull() ?: 8080
// Positional arguments (everything not starting with '-', except the value after --port)
val positionalArgs = args.filterIndexed { i, arg ->
!arg.startsWith("-") && (i == 0 || args[i - 1] != "--port")
}
val inputFile = positionalArgs.firstOrNull() ?: run {
System.err.println("Error: Missing mandatory <input-file> argument.")
exitProcess(1)
}
if (verbose) {
println("Verbose logging enabled.")
println("Port: $port")
}
println("Processing file: $inputFile")
}
Declarative CLI Parsing with Clikt
Clikt is the standard, multiplatform, and idiomatic CLI parsing library for Kotlin. It automatically generates formatted help menus, validates inputs, and supports subcommands.
Dependency (Gradle)
implementation("com.github.ajalt.clikt:clikt:5.1.0")
Creating a CLI Application
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.core.main
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.help
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.help
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.file
import com.github.ajalt.clikt.parameters.types.int
import java.io.File
class ConvertTool : CliktCommand(name = "convert") {
override fun help(context: Context) = "Converts input files between data formats."
// Flag option: --verbose or -v
private val verbose by option("-v", "--verbose", help = "Enable verbose output").flag()
// Typed option with default value
private val threads by option("-t", "--threads", help = "Number of worker threads")
.int()
.default(4)
// Positional argument requiring existing file
private val inputFile: File by argument(help = "Path to source file")
.file(mustExist = true, canBeDir = false)
override fun run() {
if (verbose) {
echo("Starting conversion on '${inputFile.name}' using $threads threads...")
}
echo("Converted ${inputFile.length()} bytes successfully.")
}
}
fun main(args: Array<String>) = ConvertTool().main(args)
Running convert --help automatically produces:
Usage: convert [<options>] <inputfile>
Converts input files between data formats.
Options:
-v, --verbose Enable verbose output
-t, --threads=<int> Number of worker threads
-h, --help Show this message and exit
Arguments:
<inputfile> Path to source file
Subcommands Architecture
Complex command-line tools (similar to git or docker) use subcommands:
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.core.main
import com.github.ajalt.clikt.core.subcommands
import com.github.ajalt.clikt.parameters.arguments.argument
class GitTool : CliktCommand(name = "mygit") {
override fun run() = Unit
}
class CloneCommand : CliktCommand(name = "clone") {
override fun help(context: Context) = "Clone a repository into a new directory"
private val repoUrl by argument(help = "URL of repository")
override fun run() {
echo("Cloning repository from $repoUrl...")
}
}
class CommitCommand : CliktCommand(name = "commit") {
override fun help(context: Context) = "Record changes to the repository"
override fun run() {
echo("Changes committed.")
}
}
fun main(args: Array<String>) = GitTool()
.subcommands(CloneCommand(), CommitCommand())
.main(args)
Best Practices
- Standard Exit Codes: Terminate successfully with exit code
0(exitProcess(0)), and return non-zero exit codes (such as1or2) when arguments are missing or execution fails. - Output Streams: Print standard progress and results to
stdout(println/echo), but direct validation errors and warnings tostderr(System.err.println). - Handle
-hand--helpFirst: Always intercept help requests before performing any argument validation or filesystem operations. - Use Established CLI Libraries for Production: Rather than writing custom regex or index-based argument parsers, use battle-tested libraries like Clikt to ensure proper handling of quoted strings, clustered short flags (e.g.
-xzvf), and terminal width wrapping.