The main Function
A main function is a conventional entry point for a standalone Kotlin application. It can accept command-line arguments; framework applications may use other entry mechanisms.
Follow the entry function into arguments, expressions and output.
You press Run and the café app springs to life. But which line runs first? In a project with hundreds of functions, the JVM needs one agreed-upon starting point, and in Kotlin that starting point is always called main.
The rule
A program starts at top-level main, no class required.
The smallest complete Kotlin program:
fun main() {
println("Pebble Café is open")
}Reading it word by word:
fundeclares a function.mainis the special name the runtime looks for.()means it takes no parameters.- The body inside
{ }runs from top to bottom; when it ends, the program ends.
It sits at the top level of a file, outside any class. Java needs public static void main(String[] args) inside a class; Kotlin needs none of that.
If you want words typed after the program name on the command line, use the second form:
fun main(args: Array<String>) {
println("Pebble Café is open")
if (args.isNotEmpty()) {
println("Serving table ${args[0]}")
}
}Running java -jar cafe.jar 7 makes args hold one string, "7", and the program prints "Serving table 7". Note that arguments always arrive as strings; turning "7" into the number 7 is your job.
main returns nothing useful. Its return type is Unit, Kotlin's word for "no meaningful value", and you do not need to write it.