The main Function
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.
The shortcut
To predict a program's behaviour, find main and read only it, jumping into other functions only when main calls them. Everything outside main just defines things; nothing happens until main asks for it.
Scan the file
It declares
fun greet() { println("Hello") }andfun main() { println("Open"); greet() }.
A classic mistake is spelling it Main or placing it inside a class without extra annotations. The runtime then cannot find the entry point and reports that no main method exists.
Drills
Answer fast — trust the rule.
Where does a Kotlin JVM program start running?
Which is a valid Kotlin entry point?
The program is started with java -jar cafe.jar 4 latte. What is args[1]?
A file defines fun open() { println("A") } and then fun main() { println("B") }. What is printed?
What is the return type of fun main() { }?
Remember
- Every program starts at top-level
main; no class needed. fun main()orfun main(args: Array<String>); arguments are strings.- To predict output, read
mainand follow only the calls it makes.
