Kotlin Multiplatform basics
suggest changeKotlin Multiplatform (KMP) lets you write code once and compile it for several platforms: the JVM (servers, desktop, Android), JavaScript (Node.js and browsers), WebAssembly, and native binaries for Windows, Linux, macOS and iOS. It's not a cross-platform UI toolkit or a virtual machine. Each target is compiled by its own Kotlin backend into normal platform code: .class files, a JavaScript module or a native executable.
The basic idea:
- code that works everywhere goes into a common source set and can use only the Kotlin standard library and multiplatform libraries
- code that needs platform APIs (
java.*, Node.js, POSIX, Win32) goes into platform source sets - common code declares what it needs with
expect, and each platform provides theactualimplementation
KMP has been stable since Kotlin 1.9.20. expect/actual functions and properties are stable; expect/actual classes are still Beta in Kotlin 2.4 and give a warning unless you opt in (shown below).
This article builds a small project for the JVM, Node.js, Windows and Linux. All examples were built with Kotlin 2.4.21 and Gradle 9.8.1 on JDK 25 on Windows. The iOS target is included in the build script, but iOS binaries can only be linked on a Mac, so that part was not built.
A minimal project
A multiplatform project uses the kotlin("multiplatform") Gradle plugin instead of kotlin("jvm"). See Gradle configuration if you're new to Gradle with Kotlin.
Project layout:
kmp-demo/
├── settings.gradle.kts
├── build.gradle.kts
├── gradle.properties
└── src/
├── commonMain/kotlin/demo/ App.kt, Platform.kt, Counter.kt
├── commonTest/kotlin/demo/ AppTest.kt
├── jvmMain/kotlin/demo/ JvmMain.kt, Platform.jvm.kt, Counter.jvm.kt
├── jsMain/kotlin/demo/ JsMain.kt, Platform.js.kt, Counter.js.kt, TimeZones.js.kt
└── nativeMain/kotlin/demo/ NativeMain.kt, Platform.native.kt, Counter.native.kt
settings.gradle.kts:
rootProject.name = "kmp-demo"
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
}
}
dependencyResolutionManagement {
repositories {
mavenCentral()
}
}
build.gradle.kts:
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
plugins {
kotlin("multiplatform") version "2.4.21"
kotlin("plugin.serialization") version "2.4.21"
}
kotlin {
jvmToolchain(25)
jvm {
@OptIn(ExperimentalKotlinGradlePluginApi::class)
mainRun { mainClass = "demo.JvmMainKt" }
}
js {
nodejs()
binaries.executable()
}
mingwX64 {
binaries.executable { entryPoint = "demo.main" }
}
linuxX64 {
binaries.executable { entryPoint = "demo.main" }
}
iosArm64() // linking needs macOS with Xcode
compilerOptions {
freeCompilerArgs.add("-Xexpect-actual-classes")
}
sourceSets {
commonMain.dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.8.0")
}
jsMain.dependencies {
implementation(npm("@js-joda/timezone", "2.22.0"))
}
commonTest.dependencies {
implementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
}
}
}
gradle.properties:
kotlin.native.ignoreDisabledTargets=true
What each part does:
- targets:
jvm(),js(),mingwX64()(Windows),linuxX64()andiosArm64()each add a target with its own compile, test and link tasks. Other common targets aremacosArm64(),linuxArm64(),iosSimulatorArm64(),androidTarget()(needs the Android Gradle plugin) andwasmJs(). binaries.executable: by default a target produces a library. This asks for a runnable program. For native targetsentryPointnames themainfunction. For the JVM,mainRun(still an experimental Gradle plugin API, hence the@OptIn) sets the main class for thejvmRuntask.sourceSets: dependencies added tocommonMainmust be multiplatform libraries. Gradle picks the right variant (JVM jar, JS klib, native klib) for each target automatically.compilerOptionsin thekotlin {}block apply to all targets. The-Xexpect-actual-classesflag is explained below. Kotlin compiler versions and experimental features covers the other compiler options.kotlin.native.ignoreDisabledTargetssilences warnings about tasks that can't run on the current machine, such as running Linux tests on Windows.
Source sets and the default hierarchy
Every target gets two source sets, <target>Main and <target>Test. On top of those, the plugin creates intermediate source sets for groups of targets that share APIs. With the targets above you get this tree:
commonMain
├── jvmMain
├── jsMain
└── nativeMain
├── mingwMain ── mingwX64Main
├── linuxMain ── linuxX64Main
└── appleMain ── iosMain ── iosArm64Main
Code in nativeMain is compiled for all native targets and can use Kotlin/Native APIs that every native platform has (such as kotlin.native.Platform and kotlinx.cinterop). linuxMain and appleMain can also use POSIX (platform.posix.*). iosMain can call Apple frameworks like platform.Foundation. Code moves up the tree when it can be shared and down when it needs something specific.
The source set a file is in decides which APIs it can see. Calling System.getProperty() in commonMain is a compile error, because there is no System class on JS or Native.
expect and actual
Common code declares what it needs with expect, without a body. Every target must provide a matching actual declaration with the same name and package.
src/commonMain/kotlin/demo/Platform.kt:
package demo
expect val platformName: String
src/jvmMain/kotlin/demo/Platform.jvm.kt:
package demo
actual val platformName: String =
"JVM ${System.getProperty("java.version")}"
src/jsMain/kotlin/demo/Platform.js.kt:
package demo
actual val platformName: String =
"JS on Node.js ${js("process.version")}"
src/nativeMain/kotlin/demo/Platform.native.kt covers Windows, Linux and iOS at once:
package demo
import kotlin.experimental.ExperimentalNativeApi
@OptIn(ExperimentalNativeApi::class)
actual val platformName: String =
"Native ${Platform.osFamily} ${Platform.cpuArchitecture}"
The .jvm.kt, .js.kt and .native.kt suffixes are only a naming convention. They avoid clashes between the generated JVM class names (Platform_jvmKt) and make it obvious which file is which in the IDE.
If one target has no actual, its compilation fails. Here an expect fun cpuCount(): Int was added to commonMain with only a JVM implementation:
e: file:///.../src/commonMain/kotlin/demo/Platform.kt:4:1 The 'expect' declaration 'cpuCount' has no 'actual' declaration in module '<commonMain> for JS'.
> Task :compileKotlinJs FAILED
You can put expect on functions, properties, classes, objects, interfaces, enums and annotations.
expect classes and actual typealias
An expect class declares a class whose members each platform implements. On the JVM an existing Java class with the same members can be the actual through a type alias:
// commonMain/Counter.kt
package demo
expect class AtomicCounter() {
fun incrementAndGet(): Int
fun get(): Int
}
// jvmMain/Counter.jvm.kt
package demo
actual typealias AtomicCounter = java.util.concurrent.atomic.AtomicInteger
// jsMain/Counter.js.kt
package demo
actual class AtomicCounter actual constructor() {
private var value = 0
actual fun incrementAndGet(): Int = ++value
actual fun get(): Int = value
}
// nativeMain/Counter.native.kt
package demo
import kotlin.concurrent.atomics.AtomicInt
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.concurrent.atomics.incrementAndFetch
@OptIn(ExperimentalAtomicApi::class)
actual class AtomicCounter actual constructor() {
private val value = AtomicInt(0)
actual fun incrementAndGet(): Int = value.incrementAndFetch()
actual fun get(): Int = value.load()
}
JavaScript is single-threaded, so a plain Int is enough there.
Without the -Xexpect-actual-classes flag, Kotlin 2.4 compiles this but warns about every expect and actual class:
w: file:///.../src/commonMain/kotlin/demo/Counter.kt:3:1 'expect'/'actual' classes (including interfaces, objects, annotations, enums, and 'actual' typealiases) are in Beta. Consider using the '-Xexpect-actual-classes' flag to suppress this warning. Also see: https://youtrack.jetbrains.com/issue/KT-61573
The flag in compilerOptions silences the warning. It doesn't change how the code compiles.
Prefer interfaces and expect functions
Because expect classes are Beta, and every platform must repeat each member exactly, a common recommendation is to use an ordinary interface in common code with an expect fun factory:
// commonMain
interface KeyValueStore {
fun put(key: String, value: String)
fun get(key: String): String?
}
expect fun createStore(name: String): KeyValueStore
class InMemoryStore : KeyValueStore {
private val map = mutableMapOf<String, String>()
override fun put(key: String, value: String) { map[key] = value }
override fun get(key: String): String? = map[key]
}
// jvmMain
import java.util.prefs.Preferences
actual fun createStore(name: String): KeyValueStore = object : KeyValueStore {
private val prefs = Preferences.userRoot().node(name)
override fun put(key: String, value: String) = prefs.put(key, value)
override fun get(key: String): String? = prefs.get(key, null)
}
// jsMain and nativeMain
actual fun createStore(name: String): KeyValueStore = InMemoryStore()
Platform implementations can have extra members and constructors, tests can use fakes, and you can also pass implementations in with plain dependency injection instead of expect.
Common code with multiplatform libraries
Most code in a KMP project is in commonMain. The standard library is multiplatform, and since Kotlin 2.x it also has common Uuid, Base64, HexFormat, Instant and Clock. The kotlinx libraries fill in the rest:
| Need | Library or API | Notes |
|---|---|---|
| collections, text, regex, math | kotlin-stdlib |
always available |
| UUIDs | kotlin.uuid.Uuid |
stable in 2.4; generateV4()/generateV7() still experimental |
| Base64, hex | kotlin.io.encoding.Base64, HexFormat |
stable |
| current time, instants | kotlin.time.Clock, kotlin.time.Instant |
stable since 2.3 |
| dates, time zones | kotlinx-datetime 0.8.0 |
LocalDate, TimeZone, arithmetic |
coroutines, Flow |
kotlinx-coroutines-core 1.11.0 |
runBlocking is JVM and Native only |
| JSON, CBOR, protobuf | kotlinx-serialization 1.11.0 |
needs the serialization compiler plugin |
| files, byte streams | kotlinx-io 0.9.1 |
Buffer, Source, Sink, SystemFileSystem |
| HTTP client and server | Ktor | client works on all targets |
| testing | kotlin.test, kotlinx-coroutines-test |
runs on every target |
src/commonMain/kotlin/demo/App.kt uses several of them:
package demo
import kotlinx.coroutines.*
import kotlinx.datetime.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlin.io.encoding.Base64
import kotlin.time.Clock
import kotlin.time.Instant
import kotlin.uuid.Uuid
@Serializable
data class Event(val id: String, val title: String, val date: LocalDate)
fun greet(name: String): String = "Hello, $name, from $platformName!"
fun daysUntil(date: LocalDate, today: LocalDate): Int = today.daysUntil(date)
suspend fun loadTitles(): List<String> = coroutineScope {
val a = async { delay(50); "Build" }
val b = async { delay(10); "Ship" }
listOf(a.await(), b.await())
}
suspend fun app() {
println(greet("KMP"))
println(Uuid.random().toString().length)
val launch = Event("a1b2c3d4", "Launch", LocalDate(2026, 12, 1))
val json = Json.encodeToString(launch)
println(json)
println(Json.decodeFromString<Event>(json).date.dayOfWeek)
val start = Instant.parse("2026-01-15T09:30:00Z")
println(start.toLocalDateTime(TimeZone.of("Europe/Warsaw")))
println(daysUntil(launch.date, LocalDate(2026, 1, 15)))
println(Clock.System.now() > start)
println(Base64.encode("kmp".encodeToByteArray()))
println(loadTitles())
}
See Dates and time for more on kotlinx-datetime.
main on each platform
Why is app() not simply suspend fun main() in commonMain? Because the JVM and JS accept a suspending main, but Kotlin/Native doesn't:
e: Entry point can not be a suspend function.
And runBlocking exists on the JVM and Native, but not on JS. So each platform gets a one-line main:
// jvmMain/JvmMain.kt and nativeMain/NativeMain.kt
package demo
import kotlinx.coroutines.runBlocking
fun main() = runBlocking { app() }
// jsMain/JsMain.kt
package demo
suspend fun main() = app()
JvmMain.kt compiles to the class demo.JvmMainKt, which is the mainClass in the build script. The native entryPoint = "demo.main" refers to the function in NativeMain.kt.
Time zones on JavaScript
kotlinx-datetime on JS uses the js-joda library, which doesn't include the time zone database. Without it, TimeZone.of("Europe/Warsaw") fails at runtime:
IllegalTimeZoneException: Invalid zone ID: Europe/Warsaw
Fixed offsets like TimeZone.of("+02:00") and TimeZone.UTC always work. For named zones, add the npm package (the jsMain.dependencies block above) and make sure the module is loaded from jsMain:
// jsMain/TimeZones.js.kt
package demo
@JsModule("@js-joda/timezone")
@JsNonModule
external object JsJodaTimeZoneModule
private val jsJodaTz = JsJodaTimeZoneModule
After adding an npm dependency, the build stops with Lock file was changed. Run the 'kotlinUpgradeYarnLock' task to actualize lock file. Run ./gradlew kotlinUpgradeYarnLock once and commit the updated kotlin-js-store/yarn.lock.
The JVM and native targets read the operating system's time zone data, so they need nothing extra.
Running on each target
Each target has its own run task:
$ ./gradlew jvmRun
$ ./gradlew jsNodeDevelopmentRun
$ ./gradlew runDebugExecutableMingwX64
The output is identical apart from the first line:
Hello, KMP, from JVM 25.0.4.1!
36
{"id":"a1b2c3d4","title":"Launch","date":"2026-12-01"}
TUESDAY
2026-01-15T10:30
320
true
a21w
[Build, Ship]
Hello, KMP, from JS on Node.js v24.16.0!
...
Hello, KMP, from Native WINDOWS X64!
...
Native targets produce standalone executables with no runtime to install:
$ ./gradlew linkReleaseExecutableMingwX64 linkReleaseExecutableLinuxX64
build/bin/mingwX64/releaseExecutable/kmp-demo.exe (3.4 MB)
build/bin/linuxX64/releaseExecutable/kmp-demo.kexe (3.6 MB)
Linux and Windows binaries can be cross-compiled from any host. The .kexe above was built on Windows and runs on Linux (tested in WSL):
$ ./kmp-demo.kexe
Hello, KMP, from Native LINUX X64!
36
...
The first native build downloads the Kotlin/Native compiler, LLVM and the sysroots (several hundred MB) into ~/.konan. Set KONAN_DATA_DIR to put them somewhere else.
Apple targets (iosArm64, macosArm64 and so on) can only be linked on macOS with Xcode installed. On Windows and Linux, Gradle disables those link tasks, so the iOS part of this project was not built. For an iOS app you would add binaries.framework() to the iOS targets and call the shared code from Swift. Building and distributing programs has more on Kotlin/Native executables, including a CLI built with the multiplatform plugin.
Testing with kotlin.test
kotlin.test gives you @Test, assertEquals, assertTrue, assertFailsWith and other assertions that work on every target. Tests in commonTest run once per target. On the JVM it uses JUnit underneath, on JS Mocha, and on Native its own runner.
src/commonTest/kotlin/demo/AppTest.kt:
package demo
import kotlinx.coroutines.test.runTest
import kotlinx.datetime.LocalDate
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class AppTest {
@Test
fun greetingMentionsPlatform() {
assertTrue(greet("test").startsWith("Hello, test, from "))
}
@Test
fun countsDays() {
assertEquals(31, daysUntil(LocalDate(2026, 2, 1), LocalDate(2026, 1, 1)))
}
@Test
fun counterIncrements() {
val c = AtomicCounter()
repeat(3) { c.incrementAndGet() }
assertEquals(3, c.get())
}
@Test
fun loadsTitlesInOrder() = runTest {
assertEquals(listOf("Build", "Ship"), loadTitles())
}
}
runTest from kotlinx-coroutines-test is the multiplatform way to test suspending code. It skips delay() with virtual time, so loadTitles() returns instantly. On JS it returns a promise the test framework waits for, which is why runBlocking isn't needed.
allTests runs the tests for every target the current machine can run:
$ ./gradlew allTests
> Task :jvmTest
> Task :jsNodeTest
> Task :mingwX64Test
> Task :allTests
BUILD SUCCESSFUL
counterIncrements tests three different AtomicCounter implementations with one test. linuxX64Test and iosArm64Test are skipped on Windows, because their test binaries can't run here.
When an assertion fails, each target reports it:
AppTest[jvm] > countsDays[jvm] FAILED
java.lang.AssertionError at AppTest.kt:17
4 tests completed, 1 failed
demo.AppTest.countsDays[mingwX64] FAILED
kotlin.AssertionError at null:-1
4 tests completed, 1 failed
demo.AppTest.countsDays[js, node] FAILED
AssertionError at kotlin\NATIVE_IMPLEMENTATIONS.kt:1
4 tests completed, 1 failed
The messages are in the HTML reports in build/reports/tests/<target>Test/, e.g. expected:<30> but was:<31> on the JVM and Expected <30>, actual <31>. on JS and Native. Tests in jvmTest or nativeTest can also test platform-specific code. Testing in CI covers running Gradle tests on every push.
Compose Multiplatform and Kotlin/Wasm
Two related technologies are worth knowing about:
- Compose Multiplatform from JetBrains is a UI framework based on Jetpack Compose. It shares UI code between Android, iOS, desktop (JVM) and web. It's a separate Gradle plugin built on top of KMP.
- Kotlin/Wasm (
wasmJs()andwasmWasi()targets) compiles Kotlin to WebAssembly.wasmJsruns in browsers and Node.js and is the usual backend for Compose on the web. The kotlinx libraries in the table above support it.
Neither is needed to share business logic between a server and a CLI, which is what most of the JVM, JS and native code in this book does.
When to use Kotlin Multiplatform
KMP works well when:
- the same logic (validation, data models, API clients, parsers, pricing rules) must run in an Android app, an iOS app and a backend
- you want a small native CLI and your dependencies are multiplatform
- you publish a library for Kotlin users on all platforms
It's more work when most of your code depends on Java libraries such as JDBC, Spring or Apache POI. Those exist only on the JVM, so that code stays in jvmMain. In that case a plain kotlin("jvm") project is simpler.
Tips
- Put code in
commonMainfirst and move it down only when it needs a platform API. The compiler shows exactly which call isn't available. - Keep
expectdeclarations small: a function or an interface factory is easier to implement and test than a largeexpect class. - Check a library's targets on Maven Central or klibs.io before adding it to
commonMain. A JVM-only library there fails dependency resolution for the other targets. - Test on every target in CI. Behaviour differs: number formatting on JS (
1.0.toString()is"1"), threads and memory on Native, time zones as shown above. - Build Apple targets on a macOS CI runner. Everything else can be built on Linux.