0
0
Kotlinprogramming~5 mins

Main function as entry point in Kotlin

Choose your learning style9 modes available
Introduction

The main function is where a Kotlin program starts running. It tells the computer what to do first.

When you want to run a Kotlin program from the command line.
When you need a clear starting point for your program.
When you want to test small pieces of code quickly.
When you create simple apps or scripts in Kotlin.
When you want to organize your program's flow from one place.
Syntax
Kotlin
fun main() {
    // code to run
}

// or with arguments
fun main(args: Array<String>) {
    // code using args
}

The main function must be named exactly main.

You can add args: Array<String> to get command line inputs.

Examples
A simple main function that prints a message.
Kotlin
fun main() {
    println("Hello, world!")
}
Main function that counts how many command line arguments were given.
Kotlin
fun main(args: Array<String>) {
    println("You passed ${args.size} arguments.")
}
Sample Program

This program starts at the main function and prints a welcome message.

Kotlin
fun main() {
    println("Welcome to Kotlin!")
}
OutputSuccess
Important Notes

Without a main function, Kotlin programs cannot run by themselves.

You can have only one main function as the entry point in a Kotlin application.

Summary

The main function is the starting point of a Kotlin program.

It can have no parameters or take an array of strings as arguments.

Use it to organize what your program does first.