Kotlin Hello World tutorial
last modified July 5, 2020
Kotlin Hello World tutorial shows how to create a Hello World program in Kotlin.
Kotlin is a statically-typed programming language that runs on the Java virtual machine.
Kotlin was created by JetBrains. Kotlin is and object-oriented and functional programming language. Kotlin was designed to be a pragmatic, concise, safe, and interoperable programming language.
Installing Kotlin compiler
From the official Github repository, we download Kotlin from the releases link. It comes in a ZIP archive. (Kotlin is built into the IntelliJ IDEA IDE.)
$ unzip kotlin-compiler-1.2.21.zip
We unzip the archive.
$ mv kotlinc ~/bin/
We move the directory into a destination of our choice.
$ export PATH=$PATH:~/bin/kotlinc/bin/
We add the path to the Kotlin compiler to .bashrc
or .profile
files.
Kotlin Hello World example
The following program prints a simple message to the console.
package com.zetcode fun main() { println("Hello, World!") }
The Kotlin source files have .kt
extension. Note that
in Kotlin we do not have to use semicolons.
package com.zetcode
A source file may start with a package
declaration.
Packages are use to organize types. Unlike Java, Kotlin does not require
the packages to match the directory structure; however, it is good practice
to do so.
fun main() { println("Hello, World!") }
The main()
function is an entry point to the program. A function
is declared with the fun
keyword. In Kotlin, we do not have to
put a function into a class. The println()
function prints a
message to the console. The main()
function takes an array of
strings as a parameter. Notice that in Kotlin the types follow the variable
names after a colon character.
Compiling Kotlin program
We are going to compile and run the program from the command line.
$ kotlinc hello.kt
With the kotlinc
compiler, we compile the source.
$ ls com/zetcode/ HelloKt.class
The compiler creates a HelloKt.class
in the com/zetcode
subfolder.
$ kotlin com.zetcode.HelloKt Hello, World!
We run the program with the kotlin
tool.
Packaging Kotlin program
Next we are going to show how to package a Kotlin program into a Java JAR file.
$ kotlinc hello.kt -include-runtime -d hello.jar
With the -include-runtime
option, we include Kotlin runtime into
the resulting JAR file.
$ java -jar hello.jar Hello, World!
We run the program with java
tool.
In this tutorial, we have created a simple program in Kotlin. The program was built and run with command line tools.
List all Kotlin tutorials.