How do I write Hello World in Kotlin?

In Kotlin, the HelloWorld.kt program can be written as a simple function like the following snippet.

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

From this little code snippet we can learn the following features of the Kotlin programming language:

  • Kotlin program saved in a file with .kt extension.
  • The fun keyword to declare a function to show you that programming can be fun again 😉
  • To declare variables we start with the variable name followed by its type separated by a colon.
  • We don’t have to end a statement with a semicolons.
  • To print we can use the println function, which is a wrapper to Java System.out.println.
  • The main function is the execution entry point of our HelloWorld program.
  • We can create functions at the top level file without creating a class.

To compile the HelloWorld.kt program we run the following command:

kotlinc HelloWorld.kt

The compiler creates a class file called HelloWorldKt.class. To run it type the following command, assumed that you’ve setup the $KOTLIN_LIB environment variable. In my case the variable is set to /usr/local/Cellar/kotlin/1.2.40/libexec/lib.

java -cp $KOTLIN_LIB/kotlin-stdlib.jar:. HelloWorldKt

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.