Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 134 ยท Testing and Tooling

Kotlin Multiplatform

Understand Kotlin Multiplatform: targets, source sets, expect/actual, what code to share, Compose Multiplatform, and how to design platform-neutral code with runnable stand-ins.

You have a mobile app on Android and iOS, a web client and a server. Each team writes the same rules again: how a price is rounded, how a date range is validated, how a request is retried. Two implementations of one rule are two chances to be wrong and to be different. Kotlin Multiplatform (KMP) lets you write that logic once, in Kotlin, and compile it for every platform you target, while the platform-specific parts (screens, files, sensors) stay native or are written separately.

The key word is sharing by choice. Multiplatform is not "write once, run anywhere" with one UI toolkit forced on you: you decide per project and per module what is shared. Some teams share only data models and networking; others share business logic and the whole UI (with Compose Multiplatform). This lesson explains the concepts: targets, source sets, expect/actual, what is worth sharing. The runner on this site compiles a single JVM file, so a real multiplatform build is impossible here: Gradle snippets are read-only, and the runnable examples show the design ideas that make shared code possible. You will even see the compiler's reaction when a single-platform build meets expect.

Targets

A target is a platform that Kotlin compiles to. The stable and widely used ones:

Target Compiles to Typical use
JVM Java bytecode Servers, desktop, shared libraries
Android Bytecode (JVM-like, with Android specifics) Android apps
iOS, macOS, Linux, Windows (Kotlin/Native) Native machine code via LLVM iOS apps, command-line tools
JavaScript JavaScript Browser, Node.js
WebAssembly (Wasm) Wasm modules Browser, runtimes

See Kotlin/JS and Kotlin/Native for the non-JVM targets in more detail. A multiplatform project declares which targets it builds (read-only):

Kotlin
// read-only example: shared/build.gradle.kts of a multiplatform library
plugins {
    kotlin("multiplatform")
}

kotlin {
    jvm()
    androidTarget()
    iosArm64()
    iosSimulatorArm64()
    js(IR) { browser() }

    sourceSets {
        commonMain.dependencies {
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
        }
        commonTest.dependencies {
            implementation(kotlin("test"))
        }
    }
}

Libraries need a multiplatform version to be used in shared code. A JVM-only library (Jackson, most of the Java ecosystem) cannot run on iOS. Kotlin's own libraries are multiplatform: kotlinx.coroutines, kotlinx.serialization, kotlinx-datetime, Ktor's client. The community also provides multiplatform database, settings, dependency-injection and image-loading libraries.

Source sets: where the code lives

The folder structure tells the compiler for which platforms a file is meant.

TEXT
shared/
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ commonMain/kotlin/        <- compiled for EVERY target
    โ”‚   โ”œโ”€โ”€ Pricing.kt
    โ”‚   โ””โ”€โ”€ Platform.kt           <- declares expect ...
    โ”œโ”€โ”€ commonTest/kotlin/        <- tests that run on every target
    โ”œโ”€โ”€ jvmMain/kotlin/           <- JVM only: java.* is available here
    โ”‚   โ””โ”€โ”€ Platform.jvm.kt       <- ... and the actual for the JVM
    โ”œโ”€โ”€ androidMain/kotlin/
    โ”œโ”€โ”€ iosMain/kotlin/           <- iOS only: Apple frameworks are available
    โ”‚   โ””โ”€โ”€ Platform.ios.kt
    โ””โ”€โ”€ jsMain/kotlin/

Code in commonMain can use only what exists on every target: the Kotlin standard library, kotlin.collections, kotlin.text, kotlin.time, and multiplatform libraries. It cannot use java.util.UUID, java.io.File or String.format, because Kotlin/Native and Kotlin/JS have no such classes. Platform source sets see their platform's full API. Intermediate source sets (for example appleMain, shared by iOS and macOS) form a hierarchy so that code shared by several but not all targets has a home.

This constraint is a feature: it forces shared code to be portable by construction, and the compiler tells you the moment you reach for something that is not.

expect and actual

Sometimes common code needs something that every platform has but implements differently: the platform's name, the current time source, a secure random generator, a database driver, how to open a URL. For those, Kotlin has expect and actual declarations. Common code expects a function or class exists; each platform source set provides the actual one (read-only):

Kotlin
// read-only example: commonMain/Platform.kt
expect fun platformName(): String

fun greeting(): String = "Hello from ${platformName()}"
Kotlin
// read-only example: jvmMain/Platform.jvm.kt
actual fun platformName(): String = "JVM ${Runtime.version().feature()}"
Kotlin
// read-only example: iosMain/Platform.ios.kt
import platform.UIKit.UIDevice

actual fun platformName(): String = UIDevice.currentDevice.systemName()

The compiler checks that every target has exactly one matching actual for each expect. If you add a new target and forget one, the build fails with an error for each missing piece, so you cannot ship a build that crashes on the new platform. expect/actual also works for classes, objects and annotations.

What if you try it in an ordinary single-platform build, like the one the runner uses?

Kotlin expect without a multiplatform project (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 answers error: 'expect' and 'actual' declarations can be used only in multiplatform projects. followed by a link to the setup guide. expect is not a general feature of the language; it belongs to the multiplatform Gradle plugin, so the example needs the project layout above.

Prefer interfaces to expect/actual

expect/actual is a sharp tool. Each use ties your shared code to a source-set layout. In many cases a plain interface declared in common code, with the platform supplying an implementation at start-up, is simpler, easier to test and works without any special language feature. This is just dependency injection from Project Structure and Modules. Here is the pattern as a runnable file; the comments mark which source set each part would live in.

Kotlin A platform interface instead of expect/actual

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.

GreetingService never imports java.util.Currency. It would compile unchanged for every target, because it knows only the Platform interface. The platform part is small and is created in one place (the app's entry point on each platform). Frameworks for dependency injection automate the wiring, but the design is just constructor parameters.

What to share

Share logic that is pure, valuable and identical across platforms:

  • Domain models and rules: pricing, validation, state machines, permissions.
  • Networking and serialization: API clients (Ktor client), DTOs, mapping to domain models.
  • Persistence layer interfaces and caching logic (with per-platform drivers).
  • Presentation logic: ViewModels, state holders and reducers that produce UI state.

And usually keep native:

  • Platform design features, animations, widgets and accessibility details (unless you choose Compose Multiplatform).
  • Code that talks to hardware or OS features: camera, notifications, biometric login.

A good test: "if this rule changes on Monday, do I want to change it in one place?" If yes, it belongs in commonMain. Here is a shared function with a tiny test harness. It uses nothing but the standard library, so it could sit in commonMain unchanged, and it can be tested with plain functions (kotlin.test is not available in the runner; on a real project you would use it in commonTest).

Kotlin Portable shared logic with a tiny test helper

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 first assertion checks the arithmetic: 1250 * 2 + 199 * 3 = 3097. The student discount takes 309 off (integer division), giving 2788. Because the integer arithmetic is the same on every target, the tests give the same result on the JVM, in the browser and on iOS. That is the trust that multiplatform gives you, as long as you stay within the portable subset. Dates and times are a good example of where to be careful: kotlin.time.Duration is portable, but java.time.LocalDate is not (use the multiplatform kotlinx-datetime library in shared code).

Compose Multiplatform

If you write your Android UI with Jetpack Compose (see Kotlin on Android), Compose Multiplatform from JetBrains lets the same @Composable functions draw on Android, iOS, desktop and the web. The UI is rendered by the framework (using Skia) rather than by native widgets. Teams that want pixel-identical screens and one UI codebase choose it; teams that need the exact native look of each platform keep SwiftUI on iOS and share only logic. Both are legitimate and can even be mixed screen by screen.

Kotlin
// read-only example: commonMain with Compose Multiplatform
@Composable
fun App() {
    MaterialTheme {
        var clicks by remember { mutableStateOf(0) }
        Button(onClick = { clicks++ }) {
            Text("Clicked $clicks times")
        }
    }
}

How iOS sees your Kotlin

Kotlin/Native compiles your shared module into an Apple framework that Swift code imports. Classes become Objective-C/Swift classes, suspend functions become async functions in Swift, and Kotlin sealed hierarchies and enums are visible but need some care for exhaustive switch. Generics are limited by the Objective-C bridge, so public APIs of a shared module are best kept simple: data classes, interfaces, plain functions. Tools such as SKIE can smooth the Swift experience. Treat the shared module's public API as a product with two audiences, Kotlin and Swift, and review it from both sides.

Adopting multiplatform step by step

  1. Start with a single JVM or Android library whose code is already pure Kotlin (models, rules).
  2. Replace JVM-only dependencies with multiplatform ones.
  3. Add iOS (or web) targets and see what the compiler rejects. Each error is a portability problem to fix.
  4. Introduce interfaces (or, where needed, expect/actual) for platform services.
  5. Move code from the apps into the shared module gradually, with tests in commonTest.

Do not share everything on day one. Share the code that hurts most when it diverges, and grow from there.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which source set is compiled for every target?

    commonMain is shared by all targets, so it can only use APIs that exist on all of them.
  2. 2. Which of these can be used in commonMain code?

    Duration is part of the multiplatform standard library. The java.* APIs and JVM-only functions do not exist on Kotlin/Native or Kotlin/JS.
  3. 3. What does an actual declaration do?

    expect states what common code needs; each platform supplies the actual implementation, and the compiler checks that none is missing.
  4. 4. What happens when you write expect fun platformName(): String in an ordinary single-platform build?

    The error is 'expect' and 'actual' declarations can be used only in multiplatform projects.
  5. 5. Why is a plain interface often preferred over expect/actual?

    An interface with an injected implementation is ordinary Kotlin and easy to test; expect/actual is best for things that really must be resolved at compile time.

Summary

  • Kotlin Multiplatform compiles shared Kotlin code to JVM, Android, iOS/native, JavaScript and Wasm targets; you choose how much to share.
  • commonMain can use only portable APIs: the standard library and multiplatform libraries, never java.*.
  • expect/actual lets common code declare something each platform implements; it requires the multiplatform Gradle plugin and fails in an ordinary build.
  • Often an injected interface is the simpler, more testable way to reach platform services.
  • Share pure, valuable logic first (models, rules, networking, presentation state); keep platform-specific UI and hardware access native, or use Compose Multiplatform for shared UI.
  • Adopt gradually, with tests in commonTest, and design the shared module's public API for both Kotlin and Swift callers.

Next: Kotlin/JS and Kotlin/Native