Thuta Learning
Kotlin
AdvancedProgrammingBeginner

Kotlin Multiplatform Fundamentals

KotlinLesson 2840 min

What you'll walk away with

  • Explain what Kotlin Multiplatform shares (logic) and what it leaves native (UI, platform services)
  • Name the roles of commonMain, platform source sets such as jvmMain and iosMain, and commonTest
  • Declare a platform-specific piece with expect/actual and describe how the compiler checks it
  • Choose between expect/actual and an interface passed into shared code
  • Recognise JVM-only APIs that must not appear in common code

Explain it simply

Kotlin Multiplatform in plain language

Kotlin Multiplatform, often shortened to KMP, lets one codebase produce code for several platforms: a JVM library for the server, an Android module, an iOS framework, a JavaScript bundle. You write the logic that is identical everywhere, such as validation, pricing rules, API models and view-model state, once in a shared module, and you write only the platform-specific parts separately. Think of a company that writes one product manual in a neutral language and keeps a short appendix for each country: the core is shared and local rules live in the appendix.

KMP shares logic, not necessarily the user interface. Each platform can keep its native UI (Jetpack Compose on Android, SwiftUI on iOS), or you can add Compose Multiplatform to share UI code as well. You decide how much to share, and you can start with a single small module.

Problem → Why → Solution

The problem: one rule written twice

A team ships the same app on Android and iOS. The price calculation, input validation and API parsing exist twice, once in Kotlin and once in Swift. A bug fixed in one copy stays live in the other for weeks, and the two copies drift apart: the Android app rounds a total one way and the iOS app another, and support has to explain why two phones show different prices.

Sharing code the old way has its own cost: a JavaScript engine or a C++ core wrapped separately for each platform adds a bridge that every developer must learn and debug. The two snippets below are the same rule written twice.

TotalWithTax.swift
// iOS app (Swift): the same rule, written a second time
func totalWithTax(cents: Int64, taxPercent: Int) -> Int64 {
    return cents + (cents * Int64(taxPercent) + 50) / 100   // rounds
}
TotalWithTax.kt
// Android app (Kotlin)
fun totalWithTax(cents: Long, taxPercent: Int): Long =
    cents + cents * taxPercent / 100          // truncates

One rule, one place

The cost of duplicate logic is not writing it twice; it is keeping two copies correct for ever. When the rule lives in one shared module, a fix, a test and a review cover every platform at once, and the platform apps shrink to what really differs: screens, device APIs and permissions.

Core concept: source sets, expect/actual and interfaces

A Kotlin Multiplatform module is organised into source sets. commonMain holds code that compiles for every target, so it may use only the common Kotlin standard library and libraries that support multiplatform, such as kotlinx.coroutines. Platform source sets such as jvmMain, androidMain and iosMain hold code for one target (or one family of targets) and may use that platform's own APIs: java.io on the JVM, android.* on Android, Apple frameworks on iOS. commonTest holds shared tests. You declare the targets in Gradle, for example jvm(), iosArm64() and iosSimulatorArm64(), and the compiler builds each target from commonMain plus that target's own source set.

Source setCompiled forMay use
commonMainevery targetcommon standard library and multiplatform libraries
jvmMainthe JVM targetJava libraries and java.* APIs
iosMainall iOS targetsApple platform frameworks through Kotlin/Native interop
commonTesttests on every targetkotlin.test

When common code needs something that differs per platform, you declare it with expect and give each target its own actual. In commonMain you write expect fun platformName(): String, and jvmMain and iosMain each supply actual fun platformName(): String with their own body. The compiler checks that every target has a matching actual; a target without one fails to compile, so a missing implementation never reaches runtime. expect and actual also work for properties and, with caveats you should check in the current documentation, for classes.

There is a second way to cross the platform boundary, and for anything with state or I/O it is usually better: define an ordinary interface in common code and pass an implementation into the shared logic. A Settings interface with getString and putString can be implemented over Android's SharedPreferences, iOS's NSUserDefaults or an in-memory map, and the shared ThemeRepository never knows which one it got. Tests simply pass a fake. Use expect/actual for tiny facts such as a platform name or a constant, and interfaces for services.

Common code must stick to what exists on every target. java.io.File, java.util.UUID, Thread and System.currentTimeMillis() are JVM APIs and do not compile in commonMain; reach for the common standard library, kotlinx-datetime, kotlinx-coroutines, Ktor and similar multiplatform libraries, or use expect/actual and interfaces. Builds also have platform constraints: Apple targets can only be compiled on macOS with Xcode, and each target has its own support status, so check the official documentation before relying on one.

Shared core, thin platform edges
  1. Write the rules once in commonMain
  2. Declare what differs: expect or interface
  3. Each target supplies its own piece
  4. Compiler combines common + one target

If common code needs a platform type such as Context or UIView, the boundary is in the wrong place: pass in an interface instead.

General pattern

expect / actual
// commonMain
expect fun platformFact(): String
fun shared(): String = "shared logic, running on " + platformFact()

// jvmMain
actual fun platformFact(): String = "JVM"

// iosMain
actual fun platformFact(): String = "iOS"

The expect declaration in commonMain gives only the signature and has no body. Every target must supply an actual with the same signature, and a common function such as shared() simply calls platformFact().

Worked example: shared logic behind a Settings interface

This file plays the role of a small shared module. The Settings interface and ThemeRepository are the 'common' part: they use only constructs that exist on every platform. The two PrefixedSettings instances stand in for platform implementations; in a real project one would wrap Android's SharedPreferences and the other iOS's NSUserDefaults. main acts like a shared test: it runs the same logic against both and asserts the results with check().

Why not expect/actual here?

Settings has state and I/O behind it, and a test wants to swap in an in-memory version. An interface does both without relying on expect/actual classes. A later section shows what the expect/actual version of a tiny fact looks like.

SharedSettings.kt
interface Settings {
    fun getString(key: String): String?
    fun putString(key: String, value: String)
}

class ThemeRepository(private val settings: Settings) {
    private val allowed = listOf("light", "dark")

    fun current(): String {
        val stored = settings.getString("theme")
        return stored?.takeIf { it in allowed } ?: "light"
    }

    fun toggle(): String {
        val next = if (current() == "dark") "light" else "dark"
        settings.putString("theme", next)
        return next
    }
}

class PrefixedSettings(
    private val prefix: String,
    val backing: MutableMap<String, String>,
) : Settings {
    override fun getString(key: String): String? = backing[prefix + key]

    override fun putString(key: String, value: String) {
        backing[prefix + key] = value
    }
}

fun main() {
    val android = PrefixedSettings("prefs.", mutableMapOf())
    val ios = PrefixedSettings("NSUserDefaults.", mutableMapOf())

    for ((label, settings) in listOf("android-like" to android, "ios-like" to ios)) {
        val repo = ThemeRepository(settings)
        check(repo.current() == "light")
        check(repo.toggle() == "dark")
        check(ThemeRepository(settings).current() == "dark")
        println("$label stores ${settings.backing}")
    }

    val corrupt = PrefixedSettings("x.", mutableMapOf("x.theme" to "neon"))
    val fallback = ThemeRepository(corrupt).current()
    check(fallback == "light")
    println("a corrupt value falls back to $fallback")
}

Code breakdown

  1. The seaminterface Settings {

    Common code talks only to this interface and never touches SharedPreferences or NSUserDefaults directly. This is the platform boundary.

  2. Shared validationreturn stored?.takeIf { it in allowed } ?: "light"

    If the stored value is null or something invalid such as 'neon', it falls back to light. The rule is written once, so it behaves identically on every platform.

  3. A platform implementationclass PrefixedSettings(

    This class stands for one 'platform' implementing Settings. Storing keys under a prefix imitates the way every platform stores its data differently.

  4. Same logic, two platformsfor ((label, settings) in listOf("android-like" to android, "ios-like" to ios)) {

    One loop runs ThemeRepository against two implementations. A shared test has exactly this shape: it asserts that every platform gives the same results.

  5. State survives a restartcheck(ThemeRepository(settings).current() == "dark")

    Creating a fresh repository and reading the stored value imitates closing and reopening the app. As long as the result is still dark, state is being saved correctly.

You should see
android-like stores {prefs.theme=dark}
ios-like stores {NSUserDefaults.theme=dark}
a corrupt value falls back to light
How shared code reaches a platform
  1. commonMain calls an interface or an expect function
  2. Gradle compiles commonMain with one target's source set
  3. The target's actual or implementation is linked in
  4. The same shared logic runs on every platform

expect and actual in a real module

A single-file program has no source sets, so expect/actual cannot run here, but in a real Gradle module it looks like this, spread over three files. greeting() is written once and returns Hello from JVM when run on the JVM target. The iOS actual uses Apple's platform.UIKit framework, which can only be written inside iosMain.

Platform.kt (commonMain, jvmMain, iosMain)
// shared/src/commonMain/kotlin/Platform.kt
expect fun platformName(): String

fun greeting(): String = "Hello from " + platformName()

// shared/src/jvmMain/kotlin/Platform.jvm.kt
actual fun platformName(): String = "JVM"

// shared/src/iosMain/kotlin/Platform.ios.kt
import platform.UIKit.UIDevice

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

A note on expect/actual classes

Using expect and actual for functions is the straightforward case, but for classes check the current Kotlin documentation: the compiler may warn or ask for an opt-in flag. That is one more reason to prefer an interface unless you have a reason not to.

The Gradle setup and the folder layout

A multiplatform module uses the kotlin("multiplatform") plugin and declares its targets in the kotlin { } block. commonMain.dependencies and commonTest.dependencies manage the dependencies of the shared code. Declaring the two iOS targets makes Kotlin create the iosMain source set for you. Check the official release pages for the versions to use, and remember that Apple targets can only be built on macOS.

shared/build.gradle.kts
plugins {
    kotlin("multiplatform") version "2.1.21"   // check the current Kotlin version
}

repositories {
    mavenCentral()
}

kotlin {
    jvm()
    iosArm64()
    iosSimulatorArm64()

    sourceSets {
        commonMain.dependencies {
            // replace <version> with the current kotlinx.coroutines release
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:<version>")
        }
        commonTest.dependencies {
            implementation(kotlin("test"))
        }
    }
}
module layout
shared/
  build.gradle.kts
  src/
    commonMain/kotlin/    shared logic, interfaces, expect declarations
    commonTest/kotlin/    shared tests, run on every target
    jvmMain/kotlin/       actual declarations for the JVM
    iosMain/kotlin/       actual declarations for all iOS targets

Interface or expect/actual?

Both cross the platform boundary, but they suit different situations. The table sums up how to choose.

SituationPreferWhy
A tiny platform fact (name, constant)expect fun / expect valone short actual per target; the compiler checks them all
A service with state or I/O (storage, HTTP, logging)an interface plus injectioneasy to fake in tests, no reliance on expect classes
Different native SDKs behind one APIan interface in common, an implementation per platformthe platform apps wire in the real one at startup

What common code may use

Developers used to the JVM tend to reach for java.* APIs by reflex. In commonMain those do not compile, so shared code has to be built on the common standard library. In the comparison below the first group is JVM-only and the second is written with the common standard library, so it compiles on every target.

JVM-only versus common
// JVM-only: does NOT compile in commonMain
import java.util.UUID
val id = UUID.randomUUID().toString()
val now = System.currentTimeMillis()

// Common: compiles on every target
val cents = 1250L
val text = "${cents / 100}.${(cents % 100).toString().padStart(2, '0')}"

In real projects

Where KMP shows up in real projects

Most teams do not start KMP with a rewrite; they start with one small piece. Existing Android and iOS apps can consume a shared module as a dependency, so migration can be gradual.

  • What is usually shared: business logic that does not touch the UI, such as networking, serialization, local databases, validation, pricing rules and view-model state.
  • Multiplatform libraries: Ktor client (HTTP), kotlinx.serialization (JSON), SQLDelight (database) and Koin (dependency injection) work in common code and pick a suitable engine for each platform behind the scenes.
  • UI: each platform can keep its native UI, or Compose Multiplatform can share UI code too; how much to share is the team's choice.
  • CI: JVM and Android tests can run on a Linux runner, while the iOS targets must be built and tested on a macOS runner. JetBrains publishes case studies where you can see how teams use it today.

Common mistakes

Common mistakes with Kotlin Multiplatform

Using a JVM-only API in commonMain

Writing java.io.File, java.util.UUID or System.currentTimeMillis() out of habit makes commonMain fail to compile. When you genuinely need something platform-specific, define an interface and inject it, or use a multiplatform library such as kotlinx-datetime.

Reaching for expect/actual for everything

Many expect classes are hard to replace with a fake in tests, and expect/actual for classes carries a caveat you must re-check against the current documentation. For anything with state or I/O prefer an interface and injection.

Leaking platform types into the shared API

If a shared function accepts Android's Context or iOS's UIView as a parameter, common code stops compiling or becomes tied to one platform. Express what you need as a small interface such as Settings and implement it on the platform side.

Assuming a green JVM test proves iOS works

Each platform has its own runtime, parts of the standard library and threading rules. Run the tests in commonTest on every target (for example jvmTest and the iOS simulator test) and include a macOS runner in CI.

Best practices

Best practices

  • Start with one small module such as validation and models, and move bigger pieces like networking later.
  • Keep the platform edges thin: tiny expect declarations and interfaces, with all the logic in commonMain.
  • Test shared code in commonTest and replace the platform with fakes.
  • Check each target's support status and the library versions in the official documentation before relying on them.

Mini challenge

Mini challenge: a time-aware greeting with a fake clock

Define a Clock interface (hourOfDay(): Int) for shared code and write greeting(clock, name). It returns 'Good morning' before 12, 'Good afternoon' before 18 and 'Good evening' otherwise. In tests, replace the Clock that stands for the real platform with a FixedClock.

  • Write the Clock interface and a FixedClock class that stores the hour
  • greeting validates the hour with require(hour in 0..23) and picks the phrase with when
  • In main, check() and print the hours 0, 11, 12, 17, 18 and 23
  • Confirm that hour 24 throws IllegalArgumentException with a message
TimeAwareGreeting.kt
// "commonMain": shared code only knows this interface
interface Clock {
    // TODO: declare hourOfDay(): Int
}

// "test code": a fake platform that always reports the same hour
// TODO: class FixedClock(...) : Clock

// TODO: require the hour to be in 0..23, then use when { } on the hour:
//       before 12 -> Good morning, before 18 -> Good afternoon, else Good evening
fun greeting(clock: Clock, name: String): String {
    TODO()
}

fun main() {
    // TODO: check the boundary hours 0, 11, 12, 17, 18 and 23, printing each result
    // TODO: check that hour 24 is rejected with the message
    //       "hour must be 0..23 but was 24"
}

Expected: It prints 0 -> Good morning, Mya; 11 -> Good morning, Mya; 12 -> Good afternoon, Mya; 17 -> Good afternoon, Mya; 18 -> Good evening, Mya; 23 -> Good evening, Mya and hour 24 rejected: hour must be 0..23 but was 24.

Show hint

Writing when { hour < 12 -> ...; hour < 18 -> ...; else -> ... } checks in order, so the boundaries come out right. Collect the expected phrases in a Map<Int, String> and loop over it. To catch IllegalArgumentException, use try/catch as an expression and take the message out of it.

Show solution
TimeAwareGreeting.kt
interface Clock {
    fun hourOfDay(): Int
}

class FixedClock(private val hour: Int) : Clock {
    override fun hourOfDay(): Int = hour
}

fun greeting(clock: Clock, name: String): String {
    val hour = clock.hourOfDay()
    require(hour in 0..23) { "hour must be 0..23 but was $hour" }
    val phrase = when {
        hour < 12 -> "Good morning"
        hour < 18 -> "Good afternoon"
        else -> "Good evening"
    }
    return "$phrase, $name"
}

fun main() {
    val expected = mapOf(
        0 to "Good morning, Mya",
        11 to "Good morning, Mya",
        12 to "Good afternoon, Mya",
        17 to "Good afternoon, Mya",
        18 to "Good evening, Mya",
        23 to "Good evening, Mya",
    )
    for ((hour, text) in expected) {
        val actual = greeting(FixedClock(hour), "Mya")
        check(actual == text) { "hour $hour: expected '$text' but was '$actual'" }
        println("$hour -> $actual")
    }

    val failure = try {
        greeting(FixedClock(24), "Mya")
        null
    } catch (e: IllegalArgumentException) {
        e.message
    }
    check(failure == "hour must be 0..23 but was 24")
    println("hour 24 rejected: $failure")
}

Quick quiz 1 / 3

Which of these cannot be used in commonMain?

Quick quiz 2 / 3

commonMain declares expect fun platformName(): String, jvmMain provides an actual, and iosMain provides none. What happens when you build the iOS target?

Quick quiz 3 / 3

Which design lets you test shared logic that needs storage without any platform code?

What to remember

  • KMP writes logic once in commonMain and keeps platform differences in source sets such as jvmMain and iosMain.
  • Every expect declaration needs an actual on each target, and a target without one fails to compile.
  • Prefer interfaces plus injection for services with state or I/O, and use expect/actual for tiny facts.
  • Common code must not use JVM-only APIs such as java.*, and iOS targets can only be built on macOS.

What is Kotlin Multiplatform — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Kotlin Multiplatform Fundamentals | Thuta Learning