The customary “Hello, World!” is a simple program that outputs Hello, World! on the screen. It is a very simple program and is often used to introduce a new programming language.

Kotlin “Hello, World!” Program

// Outputs Hello World
fun main(args : Array<String>) {
    println("Hello, World!")
}

When you run the program, the output will be:

Hello, World!

How this program works?

  1. Any line starting with // is a comment in Kotlin (similar to Java). Comments are ignored by the compiler. They are intended for person reading the code to better understand the intent and functionality of the program.
  2. fun main(args : Array<String>) { ... }This is the main function, which is mandatory in every Kotlin application. The Kotlin compiler starts executing the code from the main function.The function takes array of strings as a parameter and returns Unit. You will learn about functions and parameters in later chapters.For now, just remember that main function is a mandatory function which is the entry point of every Kotlin program. The signature of main function is:
    fun main(args : Array<String>) {
        ... .. ...
    }
  3. println("Hello, World!")The println() function prints the given message inside the quotation marks and newline to the standard output stream. In this program, it prints Hello, World! and new line.

Comparison With Java “Hello, World!” program

As you know, Kotlin is 100% interoperable with Java. Here’s an equivalent Java “Hello, World!” program.

// Java Hello World Program
class HelloWorldJava {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); 
    }
}

Important Notes

  1. Unlike Java, it is not mandatory to create a class in every Kotlin program. It’s because the Kotlin compiler creates the class for us.If you are using IntelliJ IDEA, go to Run > Edit Configurations to view this class. If you named your Kotlin file HelloWorld.kt, the compiler creates HelloWorldKt class.Kotlin compiler creates class automatically
  2. The println() function calls System.out.println() internally.If you are using IntelliJ IDEA, put your mouse cursor next to println and go to Navigate > Declaration ( Shortcut: Ctrl + B . For Mac: Cmd + B), this will open Console.kt (declaration file). You can see that println() function is internally calling System.out.println().console.kt declaration file in Kotlin

This tutorial was reposted from Programiz with additions