Skip to the workspace
Pebellslearn by building
Introduction to Kotlin  ›  Capstone Project

The main Function

main Function 12 minA 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.

kotlin / The main Function

Explore each scene at your own pace.

01 · The rule

The rule

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:

  • fun declares a function.
  • main is 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.