Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Multiplatform and Kotlin/JS, Native

Kotlin Multiplatform and Kotlin/JS, Native

Kotlin can compile not only to JVM bytecode but also to JavaScript, WebAssembly, and native machine code.

Kotlin Multiplatform (KMP for short) builds on this multi-backend capability to let the same business logic be reused across multiple platforms.


Kotlin's Four Backends

A "backend" refers to the part of the compiler that translates Kotlin source into a given kind of target code.

Kotlin source code passes through the K2 compiler front end and branches into four backends: Kotlin/JVM, Kotlin/JS, Kotlin/Wasm, and Kotlin/Native, each producing .jar/.class, .js, .wasm, and native binaries

There are currently four backends, all sharing the same language front end, so the syntax and standard library feel basically the same.

Backend Output Typical scenario Notes
Kotlin/JVM JVM bytecode (.class / .jar) Server, Android, desktop Full Java ecosystem and reflection available
Kotlin/JS JavaScript module Browser, Node.js IR backend, the only backend since Kotlin 1.9
Kotlin/Native Native executable or framework iOS, macOS, Linux, embedded Closed-world compilation, no JVM reflection
Kotlin/Wasm WebAssembly module Browser, WASI runtime Beta phase, with the goal of wasmJs The difference between wasmWasi

All four backends share the same language rules, but the platform-specific parts of the standard library differ.

For example, APIs for file I/O, threads, and time are implemented completely differently on each platform — which is why multiplatform projects split into source sets.


Kotlin/JVM

Kotlin/JVM is the most mature and widely used backend; its output is standard JVM bytecode.

It can call Java libraries directly and use JVM ecosystem tools such as reflection, annotation processors, and bytecode frameworks.

The default target is JVM 1.8 bytecode, which can be raised via jvmTarget; since Kotlin 2.2.20 it supports up to JDK 25.

Example

// File path: build.gradle.kts

plugins

{

    kotlin

(

"jvm"

)

version

"2.2.0"

}

kotlin

{

    compilerOptions

{

       

// The generated bytecode version; adjust it to the project's actual runtime environment

        jvmTarget.

set

(

org.

jetbrains

.

kotlin

.

gradle

.

dsl

.

JvmTarget

.

JVM_17

)

   

}

}

Android is essentially Kotlin/JVM too, just with Android's compilation toolchain and runtime.


Kotlin/JS

Kotlin/JS compiles Kotlin to JavaScript, and the output can run directly in a browser or Node.js.

Since Kotlin 1.9 the old Legacy backend has been removed, leaving the IR backend as the only choice.

Under the IR backend, Kotlin top-level declarations aren't exported by default; you must explicitly add @JsExport to make them callable from JavaScript.

Example

// File path: src/jsMain/kotlin/Main.kt

// external declaration: tells Kotlin that this API is provided by JavaScript

// The compiler only type-checks and generates no implementation

external fun alert

(

message

:

String

)

external

class

Console

{

    fun log

(

message

:

String

)

}

external val console

:

Console

// @JsExport: exports a function so JavaScript can call it

@JsExport

fun greetFromKotlin

(

name

:

String

)

:

String

=

"Hello, $name"

@JsExport

fun showMessage

(

text

:

String

)

{

    console.

log

(

"RUNOOB tip: $text"

)

    alert

(

text

)

}

After compilation, the JavaScript side can import these functions from the module.

Example

// File path: index.js

// After packaging, Kotlin/JS generates an ES module

import

{

greetFromKotlin

}

from

'./kotlin-app.mjs'

;

console.

log

(

greetFromKotlin

(

'RUNOOB'

)

)

;

 

// Output: Hello, RUNOOB

The output is:



你好,RUNOOB

Tip:external Declarations only describe APIs that already exist on the JS side and generate no code. If you write an external function that doesn't exist on the JS side, compilation succeeds and the error only appears at runtime. Kotlin 2.x recommends using external declarations and @JsModule, and minimizing the use of dynamic type.

Here's how to declare a Kotlin/JS target in Gradle; browser() means the runtime target is the browser.

Example

// File path: build.gradle.kts

plugins

{

    kotlin

(

"multiplatform"

)

version

"2.2.0"

}

kotlin

{

    js

{

                             

// Kotlin/JS target (IR is the only backend)

        browser

{

                   

// Browser environment

            binaries.

executable

(

)

   

// Generate directly runnable output

       

}

   

}

}


Kotlin/Native

Kotlin/Native compiles Kotlin directly to machine code; the output is a native executable or dynamic library, with no virtual machine needed.

Supported platforms include iOS, macOS, Linux, Windows, as well as Android NDK and wasm32.

The Closed-World Compilation Model

Closed-world means the compiler can see all the code the program uses at compile time.

Because of this, Kotlin/Native can perform thorough dead-code elimination, yielding small binaries and fast startup, at the cost of losing dynamic capabilities.

Capability Kotlin/JVM Kotlin/Native
Loading classes at runtime Supported Class.forName Not supported; all code must be determined at compile time
Reflection Full support for kotlin-reflect Only limited support; can't enumerate arbitrary members
Dynamic proxies Supported Not supported
Binary size Depends on the JVM runtime Can be stripped down to a very small size
Startup speed Requires JVM warm-up Near-instant startup

Kotlin/Native's memory model switched to a new concurrency model in Kotlin 1.7.20; objects no longer need to be frozen, and the restrictions on cross-thread sharing were removed accordingly.

The old memory manager was removed in Kotlin 1.9.20.

cinterop and C Library Interoperability

The cinterop tool reads C header files and automatically generates the corresponding Kotlin bindings.

To use it you provide a .def file describing the header file location and the generated package name.

Example

// File path: src/nativeInterop/cinterop/runoob.h

#ifndef RUNOOB_H

#define RUNOOB_H

// Returns the library's version number

int

runoob_version

(

void

)

;

// Adds two integers

int

runoob_add

(

int

a

,

int

b

)

;

#endif

The corresponding .def file is shown below; it has only three lines.



# File path: src/nativeInterop/cinterop/runoob.def

headers = runoob.h

package = runoob

Once the bindings are generated, Kotlin code calls C functions just like ordinary functions.

Example

// File path: src/nativeMain/kotlin/main.kt

import

runoob.runoob_add

import

runoob.runoob_version

fun main

(

)

{

    println

(

"C library version: ${runoob_version()}"

)

    println

(

"runoob_add(3, 4) = ${runoob_add(3, 4)}"

)

}

The output is:



C 库版本:1

runoob_add(3, 4) = 7

Interoperability with Objective-C / Swift

On Apple platforms, Kotlin/Native can call Objective-C directly and be called from it, while Swift uses Kotlin code through a generated framework.

Kotlin classes are exported as Objective-C classes, and suspend functions are automatically mapped to methods with a completion callback.

Example

// File path: src/iosMain/kotlin/Greeter.kt

class

Greeter

{

    fun greet

(

name

:

String

)

:

String

=

"Hello, $name"

   

// @Throws lets the Swift side see a checked exception

    @

Throws

(

IllegalArgumentException

::

class

)

    fun check

(

age

:

Int

)

:

Int

{

        require

(

age

0

)

{

"Age must be greater than 0"

}

       

return

age

   

}

}

On the Swift side, once you import the generated framework you can use it directly.

Example

// File path: iosApp/GreeterView.swift

import shared // framework generated by Kotlin/Native

let greeter = Greeter()

print(greeter.greet(name: "RUNOOB"))

The output in the Xcode console is:



你好,RUNOOB

Kotlin 2.0 also provides an experimental @ObjCName annotation that lets you customize the names exposed to Objective-C / Swift, avoiding naming conflicts.


Kotlin/Wasm

Kotlin/Wasm compiles Kotlin to WebAssembly, aiming for near-native execution speed in the browser.

It entered Beta in Kotlin 1.9.20 and offers two targets: wasmJs for browsers and wasmWasi for WASI runtimes.

Compared with Kotlin/JS, Wasm's advantage is performance closer to machine code and the ability to use WasmGC to manipulate host objects directly.

Example

// File path: build.gradle.kts

kotlin

{

    wasmJs

{

                     

// Wasm target for the browser

        browser

{

            binaries.

executable

(

)

       

}

   

}

}

Note:Kotlin/Wasm is still in Beta, and compiler and standard library APIs may change. For production projects that only need to run Kotlin in the browser, Kotlin/JS is the safer choice; consider Wasm when you want performance and can accept experimental features.


expect and actual

The core mechanism of multiplatform code is expect and actual.

In shared code you use expect to declare "there is such a thing here", and each platform provides the concrete implementation with actual.

When compiling for a given platform, the compiler replaces expect with that platform's actual.

Example

// File path: src/commonMain/kotlin/Platform.kt

// expect: declares without implementing; each platform must provide a corresponding actual

expect fun platformName

(

)

:

String

expect val isDesktop

:

Boolean

fun greeting

(

)

:

String

=

"Welcome to Kotlin Multiplatform, current platform: $platformName"

The JVM platform gives its own implementation.

Example

// File path: src/jvmMain/kotlin/Platform.kt

actual fun platformName

(

)

:

String

=

"Kotlin/JVM"

actual val isDesktop

:

Boolean

=

true

The JavaScript platform gives another implementation.

Example

// File path: src/jsMain/kotlin/Platform.kt

actual fun platformName

(

)

:

String

=

"Kotlin/JS"

actual val isDesktop

:

Boolean

=

false

Write an entry point on the JVM platform to print both.

Example

// File path: src/jvmMain/kotlin/Main.kt

fun main

(

)

{

    println

(

greeting

(

)

)

    println

(

"isDesktop = $isDesktop"

)

}

The output when running on the JVM is as follows.



欢迎使用 Kotlin 多平台,当前平台:Kotlin/JVM

isDesktop = true

Tip:expect class The difference between actual class is also supported, but from Kotlin 2.0 the compiler issues a Beta-status warning, which can be suppressed with -Xexpect-actual-classes . Wherever expect functions or interfaces can solve the problem, prefer not to use expect classes.


KMP Project Structure and Source Sets

A KMP project divides code into different source sets by platform: shared code goes in common, and platform-specific code goes in its own directory.

KMP project source set hierarchy: commonMain splits into jvmMain, nativeMain, jsMain, nativeMain further splits into iosArm64Main and linuxX64Main; expect can only be written in commonMain, actual is written in each platform's source set

A typical directory structure is as follows.



runoob-multiplatform/

├── build.gradle.kts              # 根构建脚本,声明目标平台

├── settings.gradle.kts

├── gradle/

│   └── libs.versions.toml        # 版本目录,集中管理依赖版本

└── src/

    ├── commonMain/kotlin/        # 所有平台共享的代码

    │   └── Platform.kt

    ├── commonTest/kotlin/        # 共享测试

    ├── jvmMain/kotlin/           # 仅 JVM 平台

    ├── jsMain/kotlin/            # 仅 Kotlin/JS

    ├── nativeMain/kotlin/        # 所有 Kotlin/Native 目标共享

    └── iosMain/kotlin/           # 仅 iOS 目标

Common source sets and their roles are listed below.

source set Purpose
commonMain Code shared by all targets
commonTest Shared test code
jvmMain Visible only to the JVM target
jsMain Visible only to the Kotlin/JS target
wasmJsMain Visible only to the Kotlin/Wasm target
nativeMain Shared by all Kotlin/Native targets
appleMain Shared by all Apple platform targets
iosMain Visible only to the iOS target

Intermediate layers such as nativeMain, appleMain, and iosMain are generated automatically by the default hierarchy template, enabled by default since Kotlin 1.9.20.

Declare target platforms and dependencies in the build script.

Example

// File path: build.gradle.kts

plugins

{

    kotlin

(

"multiplatform"

)

version

"2.2.0"

}

kotlin

{

   

// Declare the target platforms to compile for

    jvm

(

)

                                       

// Desktop / server

    js

{

browser

(

)

;

binaries.

executable

(

)

}

     

// Browser

    wasmJs

{

browser

(

)

}

                       

// WebAssembly(Beta)

    iosArm64

(

)

                                 

// iPhone device

    iosSimulatorArm64

(

)

                         

// Apple silicon simulator

    macosArm64

(

)

                               

// Apple silicon macOS

    sourceSets

{

       

// Dependencies shared by all platforms

        commonMain.

dependencies

{

            implementation

(

"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2"

)

       

}

       

// JVM-platform-only dependencies

        jvmMain.

dependencies

{

            implementation

(

"com.google.code.gson:gson:2.11.0"

)

       

}

       

// Shared tests

        commonTest.

dependencies

{

            implementation

(

kotlin

(

"test"

)

)

       

}

   

}

}

Multiplatform projects became stable starting in Kotlin 1.3; today they organize shared logic for Android, iOS, desktop, and backend.

Tip:Don't stuff UI code into commonMain too. KMP is for sharing business logic, networking, data models, and storage; the UI layer is usually left to Compose Multiplatform or each platform's own UI framework.


Common questions

The following questions often come up when building multiplatform projects.

Why can't java.util be used in commonMain

JVM-specific classes don't exist on JS and Native. Either replace them with multiplatform libraries like kotlinx-datetime and kotlinx-io, or isolate them using expect/actual.

Why can't reflection be used in Kotlin/Native

Under the closed-world compilation model, the compiler discards unreferenced code at compile time and there is no complete class metadata at runtime, so members cannot be enumerated as on the JVM.

Added @JsExport but JS still can't access it

Confirm you are using the IR backend and that the declaration is a public top-level function, class, or object member. Private declarations won't be exported even with the annotation.

Must expect and actual signatures match exactly

They must match. Function names, parameter types, and return types must all match; the K2 compiler since Kotlin 2.0 checks this more strictly.

Kotlin/JS or Kotlin/Wasm: how to choose

Choose Kotlin/JS if you need maturity, stability, and a rich ecosystem; try Kotlin/Wasm if you pursue performance and can accept Beta status.