Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 134 ยท Testing and Tooling

Kotlin/JS and Kotlin/Native

Learn how Kotlin compiles beyond the JVM: Kotlin/JS and Wasm in the browser, Kotlin/Native for iOS and native programs, interop with external, cinterop and suspend functions.

Most of this tutorial ran on the JVM, because that is where Kotlin started and where this site's runner lives. But the same language has other backends. Kotlin/JS turns Kotlin into JavaScript for browsers and Node.js. Kotlin/Wasm compiles to WebAssembly. Kotlin/Native compiles to machine code that needs no JVM, for iOS, macOS, Linux, Windows and embedded targets. In the last lesson you saw how multiplatform projects share code between them (Kotlin Multiplatform); this lesson looks at each non-JVM target on its own: what stays the same, what changes, and how Kotlin talks to its host platform.

None of these compilers exist in the runner here, which only builds JVM bytecode. So the platform-specific code is read-only. You will see exactly what the JVM compiler says when it meets JavaScript-only code, and runnable stand-ins show the patterns used at the language border. Treat this lesson as a map: it tells you what to expect so you can decide whether a target fits your project.

What stays the same everywhere

The language is identical: syntax, null safety, classes, generics, coroutines, the standard library. A data class, a when or a Sequence work the same on every backend. Kotlin also pins down the meaning of the core numeric types, whatever the platform does underneath. An Int is always 32 bits and wraps on overflow, a Long is 64 bits, and a String is a sequence of UTF-16 code units. On JavaScript, where every number is really a double, Kotlin's compiler still produces correct 32-bit behavior for Int and emulates Long.

Kotlin Behavior that is the same on every target

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The numbers come out the same on the JVM, in a browser and on a native binary. One line deserves attention: codePointCount comes from java.lang.String, so it works in this runner but would not compile for JS or Native. Where the common standard library and the JVM differ, shared code must use the common version. Some output details can also differ between targets, for example how a Double is converted to text, so run the tests of shared code on every target you ship.

Kotlin/JS and Kotlin/Wasm

Kotlin/JS compiles Kotlin through an intermediate representation into JavaScript (modules that run in browsers or Node.js) and can generate TypeScript declarations (.d.ts) for your exported API. A typical use is a web front end written in Kotlin, or a shared module consumed by an existing JavaScript or TypeScript application. Kotlin/Wasm targets WebAssembly, which runs in modern browsers with near-native speed; it is the foundation for Compose Multiplatform for web.

Calling the host platform needs a bridge, since Kotlin does not know the browser's types. Kotlin/JS gives you:

  • external declarations: you describe an existing JavaScript API in Kotlin syntax, and the compiler emits direct calls to it.
  • dynamic (JS target only): a type that turns off type checking for interop.
  • js("..."): inline JavaScript for one-off cases.
  • @JsExport: marks Kotlin declarations that JavaScript is allowed to call, with stable names.

Read-only examples (they need the Kotlin/JS Gradle plugin):

Kotlin
// read-only example: jsMain, needs the Kotlin/JS target
import kotlinx.browser.document
import kotlinx.browser.window
import org.w3c.dom.HTMLButtonElement

external interface Weather {          // describes the shape of a JS object
    val city: String
    val temperature: Double
}

@JsExport
class Counter {                        // callable from JavaScript: new Counter().increment()
    private var count = 0
    fun increment(): Int = ++count
}

fun main() {
    val button = document.getElementById("save") as HTMLButtonElement
    button.addEventListener("click", {
        window.alert("Saved!")
    })
}
Kotlin
// read-only example: a Promise from JavaScript used as a Kotlin suspend call
suspend fun loadWeather(city: String): Weather {
    val response = window.fetch("/api/weather?city=$city").await()
    return response.json().await().unsafeCast<Weather>()
}

await() on a JavaScript Promise is the link between worlds: a Promise becomes a suspend call, so asynchronous code looks sequential. The entire coroutines machinery from Introduction to Coroutines works in the browser, where there is only one thread and launch schedules on the event loop.

What happens if JS-only code reaches the JVM compiler, as it would if you shared it in common code by mistake?

Kotlin JavaScript-only annotation on the JVM (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with error: unresolved reference 'JsExport'. because the annotation exists only for the JS and Wasm targets. In a multiplatform project you would keep such code in jsMain (or use the common kotlin.js annotations where they exist). The error is useful: it proves the compiler checks portability for you.

Bridging callbacks into coroutines

JavaScript APIs are traditionally callback- or Promise-based. A Kotlin library hides that with suspendCoroutine or suspendCancellableCoroutine, which turn "call me back later" into a suspend function. This is the same technique the JS await() uses internally, and it works on every target. Our stand-in uses a callback API and the bridge:

Kotlin Turning a callback API into a suspend function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After the bridge, callers write straight-line code with ordinary try/catch; no pyramid of nested callbacks. Write the bridge once per API, close to the API. (suspendCancellableCoroutine is the better choice when the underlying operation can be cancelled, because it lets you register a cancellation handler.)

Typed code around untyped data

Much interop code boils down to receiving loosely typed data (a JavaScript object, a JSON payload, a map from another system) and turning it into proper Kotlin types at the border. On Kotlin/JS, dynamic and external interface do the work; the principle is to convert early and validate once. Here is the pattern with a plain Map standing in for the untyped object:

Kotlin Validate at the border, then use typed data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After parseUser, the rest of the program works with a non-null name and a real Int. The untyped world stays at the edge. The same applies to kotlinx.serialization or Jackson: decode at the boundary into data classes, and never let Any? leak inward. See Type Checks and Casts for as? and smart casts.

Kotlin/Native

Kotlin/Native compiles Kotlin to machine code with LLVM. There is no JVM, no JIT: the output is a self-contained executable or a library/framework. Supported targets include iOS, macOS, tvOS, watchOS, Linux, Windows (MinGW) and Android NDK. The main uses are:

  • sharing business logic with iOS apps (the shared module becomes a framework imported from Swift);
  • command-line tools that start instantly and need no runtime;
  • calling existing C libraries.

Memory is managed by a garbage collector (the older freezing restrictions are gone; objects can be shared between threads like on the JVM), so you rarely think about allocation. What you do notice: builds are slower than JVM builds (LLVM does a lot of work), the standard library is the common Kotlin one without java.*, and you use platform libraries (platform.posix, platform.Foundation) where you used the JDK.

A native entry point looks like any Kotlin program. Calls into C are described by a .def file and the cinterop tool, which generates Kotlin bindings for C headers. Read-only:

Kotlin
// read-only example: linuxX64Main, needs the Kotlin/Native toolchain
import kotlinx.cinterop.*
import platform.posix.*

@OptIn(ExperimentalForeignApi::class)
fun main() {
    println("Hello from native Kotlin")

    memScoped {
        val buffer = allocArray<ByteVar>(64)       // C memory, freed when the scope ends
        gethostname(buffer, 64u)
        println("Host: ${buffer.toKString()}")
    }
}
Kotlin
// read-only example: build.gradle.kts
kotlin {
    linuxX64 {
        binaries {
            executable { entryPoint = "main" }
        }
    }
}

The memScoped block is the idiom for C memory: allocations inside live until the block ends, so you cannot forget to free them. Pointer work like this is "unsafe" territory, hence the opt-in annotation. Good projects wrap such code in a small, safe Kotlin API and keep cinterop details in one place.

Choosing a target

You want... Choose
Server code, desktop tools, Android JVM / Android (the most mature path)
To share logic with an iOS app Kotlin/Native (iOS targets) in a multiplatform module
Kotlin in the browser, reusing a shared module Kotlin/JS or Kotlin/Wasm
Compose UI on the web Kotlin/Wasm with Compose Multiplatform
A small startup-fast command-line tool Kotlin/Native (or a JVM tool with native-image if you prefer the JVM ecosystem)

When in doubt, begin on the JVM, keep shared code in plain Kotlin with the common standard library, and add a second target only when it solves a real problem. The ecosystem for JS and Native is smaller than for the JVM: before you commit, check that your key libraries support the target (see Project Structure and Modules for how libraries are published, and Java Interoperability for what you lose when leaving the JVM).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement is true for Int on every Kotlin target?

    Kotlin defines Int as 32-bit with wraparound everywhere. On JS the compiler generates code that keeps this behavior.
  2. 2. What does external do in Kotlin/JS?

    An external declaration contains no implementation; it tells the compiler the shape of something that already exists in JavaScript.
  3. 3. What error does the JVM compiler give for @JsExport?

    The annotation is defined only for the JS and Wasm targets, so on the JVM it is an unresolved reference.
  4. 4. What is suspendCoroutine used for?

    It suspends the caller and gives you a continuation to resume from the callback, turning callbacks into straight-line code.
  5. 5. What does Kotlin/Native produce?

    Kotlin/Native compiles to native executables, libraries and frameworks, for example the framework iOS apps import.

Summary

  • Kotlin/JS and Kotlin/Wasm bring Kotlin to the browser and Node.js; Kotlin/Native compiles to machine code for iOS, desktop and command-line tools.
  • The language and the core semantics of Int, Long, String and Double are the same on every target; the available libraries are not.
  • JavaScript interop uses external, dynamic, js(...) and @JsExport; native interop uses cinterop and memScoped.
  • Turn callbacks and Promises into suspend functions with suspendCoroutine or await().
  • Convert untyped data into typed Kotlin at the border and keep Any? out of your core.
  • Begin on the JVM, keep shared code on the common standard library, and add JS or Native targets when they solve a concrete problem.

Next: Project: Expression Calculator