Learn
Introduction to Kotlin
The main() Function

Think of writing code like going on an adventure: we always need to start somewhere.

In Kotlin, the journey begins in the main() function.

The main() function is the “jumping off” point for our code and is the first part of our program that will execute when we run our program. It will exist in every single Kotlin project we create; in fact, without a main() function present, the program will return an error.

The syntax for the main() function looks like this:

fun main() { // Code will go here }
  • fun is a Kotlin keyword that is used to declare a function.
  • main is the required name of the starting function.
  • Following the function name is a pair of empty parentheses ().

Code that is written inside the curly brackets ({ }) is considered the “body” of a function. When we hit Enter to create a new line of code inside the body, the code will automatically indent itself:

fun main() { println("Hello, World!") }

Instructions

1.

In Main.kt, create the main() function.

Leave the body empty for now.

2.

Add the following code to the body of the main() function:

println("Coding is fun!")

Folder Icon

Take this course for free

Already have an account?