Writing your first Kotlin program

The first program that we typically write in any programming language is the “Hello, World” program. Let’s write the “Hello, World” program in Kotlin and understand its internals.

The “Hello, World!” program in Kotlin

Open your favorite editor or an IDE and create a file named hello.kt with the following code -

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

You can compile and run the program using Kotlin’s compiler like so -

$ kotlinc hello.kt
$ kotlin HelloKt
Hello, World!

You can also run the program in an IDE like Eclipse or IntelliJ. Learn how to Setup and run Kotlin programs in your system.

Internals of the “Hello, World!” program

  • Line 1. The first line is a comment. Comments are ignored by the compiler. They are used for your own sake (and for others who read your code).

    Kotlin supports two different styles of comments similar to other languages like C, C++, and Java -

    1. Single Line Comment:

      // This is a Single line comment
    2. Multi-line Comment:

         This is an example of a multi-line comment. 
         It can span over multiple lines.
  • Line 2. The second line defines a function called main.

    fun main(args: Array<String>) {
    	// ...

    Functions are the building blocks of a Kotlin program. All functions in Kotlin start with the keyword fun followed by a name of the function (main in this case), a list of zero or more comma-separated parameters, an optional return type, and a body.

    The main() function takes one argument - an Array of strings, and returns Unit. The Unit type corresponds to void in Java. It is used to indicate that the function doesn’t return any meaningful value.

    The Unit type is optional. i.e. you don’t need to declare it explicitly in the function declaration -

    fun main(args: Array<String>): Unit {	// `Unit` is optional

    If you don’t specify a return type, Unit is assumed.

    The main() function is not just any ordinary function. It is the entry point of your program. It is the first thing that gets called when you run a Kotlin program.

  • Line 3. The third line is a statement. It prints a String “Hello, World!” to standard output.

    println("Hello, World!")	// No Semicolons needed :) 

    Note that we can directly use println() to print to standard output, unlike Java where we need to use System.out.println().

    Kotlin provides several wrappers over standard Java library functions, println is one of them.

    Also, Semicolons are optional in Kotlin, just like many other modern languages.


Congratulations! You just wrote your first program in Kotlin. You learned about the main method, single-line and multi-line comments, and the println library function.

In the next article, you’ll learn how to create variables in Kotlin and also look at various data types that are supported for creating variables.