CodeBlanks Logo Icon CodeBlanks

Konan

Learn the Konan compiler.

What is Konan?

Konan is the name of the Kotlin/Native compiler. It turns Kotlin source into LLVM IR; LLVM then compiles that into native machine code.

Konan uses the LLVM toolchain; each target needs its own toolchain. It runs several LLVM passes during compilation; these optimise for size and speed. Toolchains live under the konan.home directory. Gradle calls Konan automatically via the kotlin-native plugin; you do not run commands by hand. The old name is Konan; today it is usually called the Kotlin/Native compiler, but the tool is still known as Konan.

The Konan toolchain

Konan uses a toolchain for each target. A toolchain contains LLVM and target-specific header files.

Example: the iosArm64 target needs the iOS SDK; linuxX64 needs Linux headers. Konan downloads the needed toolchain under ~/.konan. When a project builds, Konan picks the right toolchain and calls LLVM. This step is transparent to the developer; it runs through Gradle. The first build takes some time because toolchains are downloaded; later builds speed up.

Practice Write Konan info

Define object Konan. Add val version: String = "2.0" and fun info(): String that returns "Konan ${'$'}version". In main, write println(Konan.info()).

Starter code

Main.kt
// add the Konan object

fun main() {
    // print Konan.info() result
}

Sample solution

Main.kt
object Konan {
    val version: String = "2.0"
    fun info(): String = "Konan $version"
}
fun main() {
    println(Konan.info())
}

Expected output

Konan 2.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Konan produce?

  • JVM bytecode
  • A JSON file
  • JavaScript
  • LLVM IR Correct answer

Explanation: Konan turns Kotlin source into LLVM IR; LLVM produces machine code.

2 Complete the Konan info

Question
object Konan {
    val version: String = "2.0"
    fun info(): String = "Konan ${'$'}____"
}
Answer
object Konan {
    val version: String = "2.0"
    fun info(): String = "Konan ${'$'}version"
}

Explanation: ${'$'}version embeds the version into the string.

3 Match Konan parts

Term Meaning
Konan Kotlin/Native compiler
LLVM Machine code producer
~/.konan Toolchain directory
kotlin native plugin Gradle plugin

All lessons in Expert