The main() Function
In this page:
Declaring main()
The simplest entry point is fun main() { ... }, which takes no parameters. This is enough for most command-line programs, including everything covered in this course.
Example: Declaring main()
fun main() {
println("main() with no parameters")
}
Login to try C/C++/Java/PHP code in the editor
Accepting Command-Line Arguments
Kotlin also supports fun main(args: Array<String>), where args holds any arguments passed on the command line when the program is launched, such as java -jar app.jar hello world.
Note: If no arguments are passed, args is simply an empty array, not null.
Example: Accepting Command-Line Arguments
fun main(args: Array<String>) {
println("Received ${args.size} arguments")
for (arg in args) {
println("Argument: $arg")
}
}
Login to try C/C++/Java/PHP code in the editor
Calling Other Functions from main()
Real programs break work into smaller functions and call them from main. This keeps main short and readable, acting as a high-level outline of what the program does.
Example: Calling Other Functions from main()
fun greet(name: String) {
println("Hello, $name!")
}
fun main() {
greet("Kotlin")
println("Back in main() after calling greet()")
}
Login to try C/C++/Java/PHP code in the editor
Program Exit
A Kotlin program ends naturally when main finishes running its last statement. Using return inside main exits it early, skipping any code written after that line.
Note: Avoid unreachable code after return -- the compiler will warn you about it.
Example: Program Exit
fun main() {
println("Before return")
return
// The next line would never run
}
Login to try C/C++/Java/PHP code in the editor
- Defining more than one
main()function in different files without realizing which one the build actually runs. - Assuming
mainmust always take aStringarray parameter; Kotlin also allows a parameterlessfun main(). - Forgetting that code placed after a
returninsidemainwill never execute.
fun main()is the entry point of a standalone Kotlin program; execution always starts there.- Kotlin supports both
fun main()andfun main(args: Array<String>)to optionally receive command-line arguments. - Only one
mainfunction should exist per compiled entry point; multiple files can each have their own if used as separate targets. maincan call other functions, and the program ends oncemainfinishes executing.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: