Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 55 / 68

Reading Command-Line Arguments

In this lesson you will learn how to read command-line arguments in Kotlin, so values can be passed in from outside when the program runs. This is for anyone searching for "Kotlin command-line arguments how to use".

Declaring fun main(args: Array<String>) gives your main function an args array holding the command-line arguments. It is essential whenever you want a command-line tool whose options can be switched at run time.

The sample code checks whether any arguments were supplied with args.isNotEmpty(), and uses an if expression to take args[0] as the name when there is one and fall back to "Anonymous" when there is not.

A common stumbling block for beginners is forgetting the case where no argument was supplied. Reaching straight for args[0] errors out when nothing was passed, so check with args.isNotEmpty() or args.size first.

In real-world development this also serves as the foundation of simple automation scripts that branch on the values supplied at run time.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)