Command Line Arguments in Kotlin

Command-line arguments are a common way to parameterize execution of programs. For example, kotlin HelloWorld.kt uses HelloWorld.kt as an argument to the kotlin command.

import kotlin.system.exitProcess

fun main(args: Array<String>) {
    // args provides access to raw command-line arguments.
    // Note that args holds the arguments to the program.
    val argsWithProg = listOf(System.getProperty("sun.java.command")) + args.toList()
    val argsWithoutProg = args.toList()

    // You can get individual args with normal indexing.
    val arg = if (args.size > 2) args[2] else ""

    println(argsWithProg)
    println(argsWithoutProg)
    println(arg)
}

To experiment with command-line arguments it’s best to compile the Kotlin file to a JAR first.

$ kotlinc command-line-arguments.kt -include-runtime -d command-line-arguments.jar
$ java -jar command-line-arguments.jar a b c d
[command-line-arguments.jar a b c d]       
[a, b, c, d]
c

In this Kotlin version:

  1. We use args: Array<String> in the main function to access command-line arguments.
  2. To get the program name, we use System.getProperty("sun.java.command"), which gives us the JAR file name when executed.
  3. We create argsWithProg by combining the program name with the arguments.
  4. argsWithoutProg is simply the args converted to a list.
  5. We check the size of args before accessing the third argument to avoid an IndexOutOfBoundsException.

Note that in Kotlin, we don’t need to explicitly import standard library functions like println, as they’re available by default.

Next, we’ll look at more advanced command-line processing with command-line option parsing libraries in Kotlin.