Kotlin Multiplatform fundamentals
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 inandroidMainandiosMain, 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 anexpectdeclaration incommonMainwith anactualin each platform source set. Good for small primitives such as functions and properties.expect/actualclasses are still Beta.
| Concern | commonMain | androidMain | iosMain |
|---|---|---|---|
| Business logic | Most of it | Platform-specific parts | Platform-specific parts |
| Ktor client | ktor-client-core | OkHttp engine | Darwin engine |
| DI | Koin modules | Android bindings (e.g. Context) | iOS bindings |
| UI | None, or Compose Multiplatform | Jetpack Compose | SwiftUI/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 plugincom.android.kotlin.multiplatform.librarywithkotlin { android { } }; the oldercom.android.library+androidTarget()setup relies on APIs deprecated in AGP 9. commonMainis the root source set.androidMainis the Android target's source set;iosMainis an intermediate source set the default hierarchy template creates for all iOS targets.- Each iOS target (
iosArm64,iosSimulatorArm64, and the lower-tieriosX64for Intel Mac simulators) gets its own leaf source set;iosMainis their shared parent, so most iOS code goes there. - Prefer an interface plus DI for most platform abstractions; keep
expect/actualfor small primitives.expect/actualclasses are Beta. - Ktor client uses a different engine per platform: OkHttp on Android, Darwin on iOS;
ktor-client-corelives incommonMain. - 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
.frameworkfor Xcode when you declarebinaries.framework; the exported Objective-C header lets Swift call Kotlin code. - Swift sees
suspendfunctions as completion handlers (callable withasync);Flowneeds SKIE or KMP-NativeCoroutines for idiomaticAsyncSequenceuse. - 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-coreand the JSON setup go incommonMain; the OkHttp and Darwin engines go in their platform source sets so each target links the right HTTP stack.iosMaincomes from the default hierarchy template and is the parent ofiosArm64MainandiosSimulatorArm64Main, so a dependency oractualdeclared there is visible to both iOS targets.- The serialization compiler plugin is required for
@Serializableclasses; the JSON library alone is not enough. - In an older project you will see
id("com.android.library")withandroidTarget()and a separate top-levelandroid { }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,
SharedRepositorylives incommonMain,AndroidPlatforminandroidMainandIosPlatforminiosMain; each app build only contains its own implementation.
In production
- A team's shared module had been set up by hand before the default hierarchy template existed, with
actualdeclarations living only in theiosArm64Mainleaf 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
expectdeclarations had noactualfor the new target. Nobody noticed until CI, because developers only built the device framework locally.
- Removed the manual
dependsOnwiring so the default hierarchy template applied, and moved theactualdeclarations fromiosArm64MainintoiosMain, 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
iosMainunless it is truly specific to one target.
- A shared presenter in
commonMainlaunched its work onDispatchers.Main. - The app ran fine on Android and iOS, but the shared tests failed when run on the JVM/Android host with an
IllegalStateExceptionabout the Main dispatcher being missing or failing to initialize. - Host unit tests have no Android main looper or UI thread, so
Dispatchers.Mainhas nothing to dispatch to.
- Added
kotlinx-coroutines-testtocommonTestand calledDispatchers.setMain(StandardTestDispatcher())before each test andDispatchers.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 withrunTest. - 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
commonMainwith per-platform implementations injected by DI is easier to test and swap. - Android imports in commonMain. Importing
android.util.LogorContextincommonMaindoes not compile, becausecommonMaincannot see Android APIs. Define an interface incommonMainand implement it inandroidMainandiosMain. - Putting iOS actuals in one leaf source set. An
actualiniosArm64Mainonly covers the device. Put shared iOS code iniosMainso 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-coreincommonMainwithout an engine inandroidMainoriosMainmeansHttpClient()has no engine to use at runtime. Each platform needs its own engine dependency. - Exposing Flow to Swift directly. Swift sees a Kotlin
Flowonly as a generic Objective-C interface with noAsyncSequencesupport, 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.
- In a new Gradle project (or from the Kotlin Multiplatform wizard), apply
kotlin("multiplatform")and the Android-KMP library plugincom.android.kotlin.multiplatform.libraryinshared/build.gradle.kts. - Inside
kotlin { }, configureandroid { namespace = ...; compileSdk = ...; minSdk = ... }, then declareiosArm64()andiosSimulatorArm64()and give bothbinaries.framework { baseName = "Shared" }. - In
commonMain, define an interfacePlatformInfowith a single methodfun name(): String. - In
androidMain, implementPlatformInfoasAndroidInforeturning the string "Android". - In
iosMain, implementPlatformInfoasIosInforeturning the string "iOS". - In
commonMain, write a top-level functionfun describe(info: PlatformInfo): Stringthat returns "Running on " + info.name(). - Run
./gradlew :shared:buildand then./gradlew :shared:linkDebugFrameworkIosSimulatorArm64.
Done when: both commands end with BUILD SUCCESSFUL and Shared.framework exists under shared/build/bin/iosSimulatorArm64/debugFramework/.