The main function
- Kotlin course
- Beginner
- Lesson 3/116
- 4 min
Learn the fun main(args: Array<String>) structure.
The main function
In Kotlin, the main function is where a program starts. Its simplest form is fun main(); it takes no parameters. To access command-line arguments, use the signature fun main(args: Array<String>).
Here args is an array of strings; each argument given with the program is read as args[0], args[1], and so on. If the program is run with no arguments, args.size is zero.
Practice Print args
Write a fun main(args: Array<String>). Print the array length with println(args.size).
Sample solution
fun main(args: Array<String>) {
println(args.size)
}Expected output
0
Which main signature?
Kotlin 2.x has two common main signatures: fun main() and fun main(args: Array<String>). Use the first for simple programs and the second when you need command-line arguments.
Whichever you choose, the program's entry point is always a function named main. IntelliJ IDEA supports both forms.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the signature
fun main(args: Array<String____>) { }
fun main(args: Array<String>>) { }
Explanation: Array<String> is the type of an array of strings.
2 What is args an instance of?
- Int
- Boolean
- Array<String> Correct answer
- Char
Explanation: args is an Array<String>; that is, an array of strings.
3 Match the concepts
| Term | Meaning |
|---|---|
main |
Entry point |
args |
Command-line arguments |
Array<String> |
Array type |
println |
Output |