Kotlin “Hello, World!” Program

How this program works?

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.

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>) {
... .. ...
}

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.

Important Notes

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.

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().

Resources

This website uses cookies to improve your experience and to personalise content and adverts, to provide social media features and to analyse traffic. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRejectRead More