Hello, World

In this short tutorial, we’re going to look at an all-time classic, a Hello, World program. Before starting, you’ll need to know the very basics of:

Create a new directory for this project. Inside the directory, initialize Gradle by executing

$ gradle init

Open build.gradle and paste the following:

plugins {
    id "org.jetbrains.kotlin.konan" version "1.3.11"
}

konanArtifacts {
    program "hello"
}

Konan is the name of the Kotlin/Native plugin for Gradle. It will help us compile the program specified in konanArtifacts. The name of the program is hello, but you can change it to whatever you like.

By convention, the plugin expects source code to reside in src/main/kotlin. Go ahead and create a src/main/kotlin/Hello.kt file in your project directory. Then, add the following:

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

As you can see, there is no difference between a Kotlin/Native Hello World and a Kotlin Hello World. Under the hood, however, a few things do differ.

Strings, such as "Hello, Kotlin/Native!", can be represented differently on various platforms. The Kotlin/Native String class, also known as KString, hides away this complexity. The same is true for Array type. According to the Kotlin/Native interop docs, it is represented as a CPointer<T>? class when interacting with a C library, which supports the [] operator for accessing values by index.

It’s now clear that Kotlin/Native hides away some of the multiplatform complexities, and makes it easy for developers to just worry about the code they write.

To build the project, run gradle build. Once successfully built, the executable is placed in the build/konan/bin/{platform} folder, where platform denotes your underlying OS. On a Mac, your build folder might look like this:

the build folder

The executable name is equal to the name of the program specified in konanArtifacts. The .kexe extension is an abbreviation for Kotlin executable. To run the program, you can either execute gradle run, or invoke the .kexe file directly.