Kotlin Multiplatform fundamentals

Learn Kotlin Multiplatform fundamentals: source sets, targets, the KMP Gradle plugin and Android-KMP library setup for sharing Kotlin code with iOS. About 22 minutes.

Why it matters

  • Kotlin Multiplatform lets one team maintain shared business logic for Android and iOS, removing the duplicate code and behaviour drift that come from writing the same rules twice in two native codebases.
  • Interviewers ask about KMP to test whether you can reason beyond a single platform and choose the right abstraction layer.
  • The source-set model and platform abstractions (interfaces or expect/actual) appear in system-design questions about cross-platform architecture and dependency boundaries.
  • Knowing when NOT to use KMP (heavy platform-specific UI, deep OS integration, a team with no iOS build experience) is as important as knowing when to use it; a senior answer names the trade-off.

The simple explanation

Kotlin Multiplatform (KMP) is Kotlin's stable technology for sharing code between platforms. You write common code once in commonMain, and the Kotlin compiler builds it for each target: JVM bytecode for Android and native binaries for iOS through Kotlin/Native. You choose how much to share, from a single data layer up to the UI with Compose Multiplatform.

  • A restaurant group writes one recipe book (commonMain) used by every location.
  • Each kitchen (androidMain, iosMain) has its own equipment and local suppliers.
  • The recipe says "use a knife" (an interface); each kitchen brings its own knife (the platform implementation).
  • The head chef (the Gradle plugin) decides which kitchens exist and which recipes each one receives.
  • Opening a new location (adding a target such as iosSimulatorArm64()) means every platform-specific step must also exist for that kitchen before the recipe book compiles.

The entry point is the Kotlin Multiplatform Gradle plugin, kotlin("multiplatform") (id org.jetbrains.kotlin.multiplatform). For the Android target of a shared library module, current Android guidance is the Android-KMP library plugin com.android.kotlin.multiplatform.library, configured in an android { } block inside kotlin { }. Older projects apply com.android.library and call androidTarget(); that combination depends on APIs deprecated in Android Gradle Plugin 9, so plan a migration.

Source sets are the core mechanism. With the default hierarchy template, commonMain is shared by every target, androidMain holds Android-only code, and iosMain is an intermediate source set shared by the iOS targets (iosArm64Main, iosSimulatorArm64Main, and iosX64Main if you still build for Intel Mac simulators). Code in commonMain may only call APIs available on every target; platform code lives in a platform or intermediate source set.

Platform abstraction has two patterns:

  • Interface + DI: define an interface in commonMain, implement it in androidMain and iosMain, and inject it (for example with Koin). The Kotlin docs recommend standard constructs like this wherever possible; it is easy to fake in tests.
  • expect/actual: the compiler matches an expect declaration in commonMain with an actual in each platform source set. Good for small primitives such as functions and properties. expect/actual classes are still Beta.
ConcerncommonMainandroidMainiosMain
Business logicMost of itPlatform-specific partsPlatform-specific parts
Ktor clientktor-client-coreOkHttp engineDarwin engine
DIKoin modulesAndroid bindings (e.g. Context)iOS bindings
UINone, or Compose MultiplatformJetpack ComposeSwiftUI/UIKit, or Compose Multiplatform

For iOS, you declare binaries.framework on each iOS target and Kotlin/Native produces a .framework that Xcode links. Swift sees the shared code through a generated Objective-C header: suspend functions arrive as completion handlers, which Swift can also call with async/await, and a Flow needs a wrapper such as SKIE or KMP-NativeCoroutines to be consumed comfortably as an AsyncSequence. Direct Swift export is still experimental. See the expect/actual and source-sets lesson for the declaration syntax, and the KMP architecture and DI lesson for wiring Koin across targets.

Notes

  • Kotlin Multiplatform is stable; Compose Multiplatform (shared UI) is a separate, optional layer on top of it.
  • Apply kotlin("multiplatform") to the shared module. For the Android target, use the Android-KMP library plugin com.android.kotlin.multiplatform.library with kotlin { android { } }; the older com.android.library + androidTarget() setup relies on APIs deprecated in AGP 9.
  • commonMain is the root source set. androidMain is the Android target's source set; iosMain is an intermediate source set the default hierarchy template creates for all iOS targets.
  • Each iOS target (iosArm64, iosSimulatorArm64, and the lower-tier iosX64 for Intel Mac simulators) gets its own leaf source set; iosMain is their shared parent, so most iOS code goes there.
  • Prefer an interface plus DI for most platform abstractions; keep expect/actual for small primitives. expect/actual classes are Beta.
  • Ktor client uses a different engine per platform: OkHttp on Android, Darwin on iOS; ktor-client-core lives in commonMain.
  • Hilt and Dagger are Android/JVM-only; Koin is the most common DI choice for Kotlin Multiplatform commonMain, and manual constructor injection works everywhere.
  • Kotlin/Native produces a .framework for Xcode when you declare binaries.framework; the exported Objective-C header lets Swift call Kotlin code.
  • Swift sees suspend functions as completion handlers (callable with async); Flow needs SKIE or KMP-NativeCoroutines for idiomatic AsyncSequence use.
  • Shared libraries: Ktor, kotlinx.serialization, kotlinx.coroutines, SQLDelight or Room (Room supports KMP), and DataStore all have multiplatform artifacts.
  • Building iOS targets requires a Mac with Xcode, so CI for a KMP project needs a macOS runner.

Code example

This is the build.gradle.kts for a KMP shared module using the current Android-KMP library plugin. It declares the Android target and two iOS targets, builds an iOS framework, and wires Ktor, coroutines and serialization into the right source sets so each platform gets its own HTTP engine. The libs. aliases come from the project's version catalog (gradle/libs.versions.toml), which is where versions belong.

// shared/build.gradle.kts
plugins {
    alias(libs.plugins.kotlinMultiplatform)              // org.jetbrains.kotlin.multiplatform
    alias(libs.plugins.androidKotlinMultiplatformLibrary) // com.android.kotlin.multiplatform.library
    alias(libs.plugins.kotlinSerialization)              // org.jetbrains.kotlin.plugin.serialization
}
 
kotlin {
    // Android target, configured by the Android-KMP library plugin
    android {
        namespace = "com.example.shared"
        compileSdk = libs.versions.android.compileSdk.get().toInt()
        minSdk = libs.versions.android.minSdk.get().toInt()
    }
 
    // iOS targets: each one builds a framework that Xcode links
    listOf(iosArm64(), iosSimulatorArm64()).forEach { target ->
        target.binaries.framework {
            baseName = "Shared"
        }
    }
 
    sourceSets {
        commonMain.dependencies {
            implementation(libs.kotlinx.coroutines.core)
            implementation(libs.ktor.client.core)
            implementation(libs.ktor.client.content.negotiation)
            implementation(libs.ktor.serialization.kotlinx.json)
        }
        androidMain.dependencies {
            implementation(libs.ktor.client.okhttp)
        }
        iosMain.dependencies {
            implementation(libs.ktor.client.darwin)
        }
    }
}
  • ktor-client-core and the JSON setup go in commonMain; the OkHttp and Darwin engines go in their platform source sets so each target links the right HTTP stack.
  • iosMain comes from the default hierarchy template and is the parent of iosArm64Main and iosSimulatorArm64Main, so a dependency or actual declared there is visible to both iOS targets.
  • The serialization compiler plugin is required for @Serializable classes; the JSON library alone is not enough.
  • In an older project you will see id("com.android.library") with androidTarget() and a separate top-level android { } block. That setup still appears in tutorials, but it depends on APIs deprecated in AGP 9.

Run the idea in plain Kotlin

interface Platform {
  fun name(): String
}

class AndroidPlatform : Platform {
  override fun name(): String = "Android"
}

class IosPlatform : Platform {
  override fun name(): String = "iOS"
}

class SharedRepository(private val platform: Platform) {
  fun describe(): String {
      return "Repository running on " + platform.name()
  }
}

fun main() {
  val androidRepo = SharedRepository(AndroidPlatform())
  val iosRepo = SharedRepository(IosPlatform())
  println(androidRepo.describe())
  println(iosRepo.describe())
  println("Same class, different platform implementation")
}

Expected output:

Repository running on Android
Repository running on iOS
Same class, different platform implementation
  • In a real KMP module, SharedRepository lives in commonMain, AndroidPlatform in androidMain and IosPlatform in iosMain; each app build only contains its own implementation.

In production

Missing actual for a new iOS target
  • A team's shared module had been set up by hand before the default hierarchy template existed, with actual declarations living only in the iosArm64Main leaf source set.
  • They added iosSimulatorArm64() so developers on Apple silicon Macs could run the app in the simulator.
  • Builds for the device still passed, but every simulator build failed with errors saying the expect declarations had no actual for the new target. Nobody noticed until CI, because developers only built the device framework locally.
The fix
  • Removed the manual dependsOn wiring so the default hierarchy template applied, and moved the actual declarations from iosArm64Main into iosMain, so every iOS target shares them.
  • Configured CI on a macOS runner to compile all targets (for example ./gradlew build), not just the device target.
  • Documented that new iOS code goes in iosMain unless it is truly specific to one target.
Main dispatcher missing in shared unit tests
  • A shared presenter in commonMain launched its work on Dispatchers.Main.
  • The app ran fine on Android and iOS, but the shared tests failed when run on the JVM/Android host with an IllegalStateException about the Main dispatcher being missing or failing to initialize.
  • Host unit tests have no Android main looper or UI thread, so Dispatchers.Main has nothing to dispatch to.
The fix
  • Added kotlinx-coroutines-test to commonTest and called Dispatchers.setMain(StandardTestDispatcher()) before each test and Dispatchers.resetMain() after it.
  • Replaced hard-coded background dispatchers in the shared classes with an injected CoroutineDispatcher, so tests pass a test dispatcher and control time with runTest.
  • The same tests now run on every target in CI.

Common mistakes

  • expect/actual for every platform difference. It spreads platform declarations across every source set and makes fakes harder. An interface in commonMain with per-platform implementations injected by DI is easier to test and swap.
  • Android imports in commonMain. Importing android.util.Log or Context in commonMain does not compile, because commonMain cannot see Android APIs. Define an interface in commonMain and implement it in androidMain and iosMain.
  • Putting iOS actuals in one leaf source set. An actual in iosArm64Main only covers the device. Put shared iOS code in iosMain so new iOS targets inherit it, and compile every target in CI.
  • Hilt in commonMain. Hilt is Android-only and will not compile for iOS. Use Koin or manual constructor injection in commonMain, and keep Hilt (if you want it) in the Android app module.
  • Forgetting the Ktor engine. Declaring ktor-client-core in commonMain without an engine in androidMain or iosMain means HttpClient() has no engine to use at runtime. Each platform needs its own engine dependency.
  • Exposing Flow to Swift directly. Swift sees a Kotlin Flow only as a generic Objective-C interface with no AsyncSequence support, so collecting it is awkward and easy to leak. Wrap it with SKIE or KMP-NativeCoroutines, or expose a callback-based API.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is Kotlin Multiplatform and when would you choose it over a native-only approach?”

“Explain how KMP source sets and the default hierarchy template work.”

“When should you use expect/actual versus an interface with dependency injection?”

“How does Kotlin/Native interop with Swift work, and what are the limitations?”

Quiz

What is the root source set in a KMP module?

Which of these DI frameworks works in commonMain across both Android and iOS?

What does Kotlin/Native produce for Xcode when you declare binaries.framework on an iOS target?

How does Swift see a Kotlin suspend function exported from KMP?

0 of 4 answered

Mini task

Create a minimal KMP module with a shared interface and two platform implementations. Building the iOS targets needs a Mac with Xcode.

  1. In a new Gradle project (or from the Kotlin Multiplatform wizard), apply kotlin("multiplatform") and the Android-KMP library plugin com.android.kotlin.multiplatform.library in shared/build.gradle.kts.
  2. Inside kotlin { }, configure android { namespace = ...; compileSdk = ...; minSdk = ... }, then declare iosArm64() and iosSimulatorArm64() and give both binaries.framework { baseName = "Shared" }.
  3. In commonMain, define an interface PlatformInfo with a single method fun name(): String.
  4. In androidMain, implement PlatformInfo as AndroidInfo returning the string "Android".
  5. In iosMain, implement PlatformInfo as IosInfo returning the string "iOS".
  6. In commonMain, write a top-level function fun describe(info: PlatformInfo): String that returns "Running on " + info.name().
  7. Run ./gradlew :shared:build and then ./gradlew :shared:linkDebugFrameworkIosSimulatorArm64.

Done when: both commands end with BUILD SUCCESSFUL and Shared.framework exists under shared/build/bin/iosSimulatorArm64/debugFramework/.

Next: expect/actual and source sets