Kotlin Multiplatform cheat sheet
Key ideas
commonMainis the root source set;androidMainandiosMainare platform source sets created by the default hierarchy template (Kotlin 1.9.20+).- Prefer an interface plus DI (Koin) for platform abstractions; keep
expect/actualfor small primitives like platform name or UUID. - Ktor client uses OkHttp on Android and Darwin on iOS;
ktor-client-corelives incommonMain, each engine in its platform source set. - Hilt and Dagger are Android/JVM-only; use Koin or manual constructor injection in
commonMainso shared code compiles for iOS. - Kotlin/Native produces a
.frameworkfor Xcode; Swift seessuspendas completion handlers, butFlowneeds SKIE or KMP-NativeCoroutines. - Compose Multiplatform uses the same
androidx.compose.*packages; iOS renders via Skia into a Metal layer, so text metrics differ from Android. - A single
Json { ignoreUnknownKeys = true }incommonMainprevents additive backend changes from breaking older clients on either platform. - Building iOS targets requires a Mac with Xcode; CI for a KMP project needs a macOS runner.
expect/actualclasses are Beta in Kotlin 2.x; add-Xexpect-actual-classesto suppress the warning, but prefer interfaces instead.
APIs at a glance
| API or term | Use it for |
|---|---|
kotlin("multiplatform") | Gradle plugin applied to the shared module to enable KMP targets. |
com.android.kotlin.multiplatform.library | Android-KMP library plugin; replaces the older com.android.library + androidTarget() setup deprecated in AGP 9. |
expect / actual | Compile-time platform-specific declarations for small primitives; classes are Beta. |
startKoin / module | Multiplatform DI; single for app-wide objects, factory for per-screen, scopes for session state. |
ktor-client-core / ktor-client-okhttp / ktor-client-darwin | Shared HTTP client in commonMain; per-platform engine in androidMain or iosMain. |
@Serializable / kotlinx.serialization | JSON (de)serialization in commonMain; pair with ContentNegotiation in the shared HttpClient. |
binaries.framework | Produces a .framework that Xcode links; dynamic by default, set isStatic = true if a dynamic one causes duplicate-symbol or linking errors. |
ComposeUIViewController | iOS entry point from androidx.compose.ui.window; wrap in UIViewControllerRepresentable for SwiftUI. |
SKIE / KMP-NativeCoroutines | Bridge Kotlin Flow to Swift AsyncSequence; neither ships with Compose Multiplatform. |
@Throws | Propagate a specific Kotlin exception to Swift as NSError; without it, a suspend function only propagates CancellationException. |
@ObjCName | Set a custom Objective-C and Swift name for an exported symbol; requires @OptIn(ExperimentalObjCName::class). |
iosArm64() / iosSimulatorArm64() | iOS targets for device and Apple Silicon simulator; iosX64() is only for Intel Macs and is being phased out. |
Snippets
Shared module Gradle build
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidKotlinMultiplatformLibrary)
alias(libs.plugins.kotlinSerialization)
}
kotlin {
android {
namespace = "com.example.shared"
compileSdk = libs.versions.android.compileSdk.get().toInt()
minSdk = libs.versions.android.minSdk.get().toInt()
}
listOf(iosArm64(), iosSimulatorArm64()).forEach { target ->
target.binaries.framework { baseName = "Shared" }
}
sourceSets {
commonMain.dependencies {
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) }
}
}expect/actual for primitives, interface for the rest
// commonMain
expect fun platformName(): String
interface KeyValueStorage {
fun save(key: String, value: String)
fun load(key: String): String?
}
// androidMain
actual fun platformName(): String = "Android ${Build.VERSION.SDK_INT}"
// iosMain
actual fun platformName(): String =
UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersionKoin shared module with platform boundary
interface AuthRepository { suspend fun login(email: String, password: String): Boolean }
class KtorAuthRepository(private val client: HttpClient) : AuthRepository {
override suspend fun login(email: String, password: String): Boolean =
client.submitForm("https://api.example.com/login", parameters {
append("email", email); append("password", password)
}).status.isSuccess()
}
class LoginPresenter(private val auth: AuthRepository)
expect val platformModule: Module // each platform declares `actual val platformModule = module { ... }`
val sharedModule = module {
single { HttpClient { install(ContentNegotiation) { json() } } }
singleOf(::KtorAuthRepository) bind AuthRepository::class
factoryOf(::LoginPresenter)
}
fun initKoin(config: KoinAppDeclaration? = null) {
startKoin {
config?.invoke(this)
modules(sharedModule, platformModule)
}
}Swift-safe suspend API with @Throws
// commonMain (IOException from kotlinx.io)
@Serializable
data class User(val id: String, val name: String)
interface UserApi {
suspend fun user(id: String): User?
fun userUpdates(): Flow<List<User>>
}
class UserRepository(private val api: UserApi) {
@Throws(IOException::class)
suspend fun fetchUser(id: String): User? = api.user(id)
fun observeUsers(): Flow<List<User>> = api.userUpdates()
}Rules of thumb
- Prefer an interface in
commonMainplus DI overexpect/actualfor any platform abstraction larger than a one-line primitive. - Never import
android.*,platform.Foundation, orjava.*incommonMain; define an interface and implement it per platform. - Never use Hilt or Dagger in
commonMain; use Koin or manual constructor injection so the graph compiles for iOS. - Always declare both
iosArm64()andiosSimulatorArm64();iosX64()is only for Intel Mac simulators and is being phased out. - Prefer a single
Json { ignoreUnknownKeys = true }incommonMainso additive backend changes do not break older clients. - Never hand-collect a
Flowin Swift; wrap it with SKIE or KMP-NativeCoroutines and tie collection to a cancellableTask.
Gotchas
- Using expect/actual for every platform difference (repositories, use cases). It spreads declarations across every source set, forces each target to implement the whole class, and makes fakes in
commonTestawkward; use an interface incommonMainwith DI instead. - Importing android.util.Log or Context in commonMain.
commonMaincannot see Android APIs, so the code will not compile; define an interface incommonMainand implement it inandroidMainandiosMain. - Declaring ktor-client-core in commonMain without an engine in a platform source set.
HttpClient()has no engine at runtime and crashes; addktor-client-okhttptoandroidMainandktor-client-darwintoiosMain. - Exposing a Kotlin Flow to Swift without a bridge. Swift sees a plain Objective-C protocol with no type parameter and no cancellation handle, so hand-written collectors leak; add SKIE or KMP-NativeCoroutines.
- Omitting @Throws on a suspend function that can throw IOException. Without it, only
CancellationExceptionpropagates asNSError; any other Kotlin exception terminates the iOS app, so annotate the API or return a sealed result type. - Calling startKoin more than once. A second call throws
KoinApplicationAlreadyStartedException; start Koin once at app launch and use Koin scopes for shorter lifetimes.
Quick interview answers
Why should I avoid expect/actual classes for a repository in KMP?
expect/actual classes are still Beta in Kotlin 2.x and allow only one implementation per target, which makes fakes in commonTest difficult. Define an interface in commonMain and inject the platform implementation with Koin or constructor injection instead.
How does Ktor handle platform-specific HTTP engines in a KMP project?
ktor-client-core lives in commonMain and the shared code only references HttpClient. Each platform source set adds its own engine dependency: ktor-client-okhttp in androidMain and ktor-client-darwin in iosMain, often passed into HttpClient(engine) through an expect fun createEngine().
How does Swift call a Kotlin suspend function, and what happens with Flow?
Kotlin/Native exports suspend functions as Objective-C methods with a completion handler, callable with try await in Swift 5.5+. Flow exports as a type-erased Objective-C protocol, so you need SKIE or KMP-NativeCoroutines to get an idiomatic AsyncSequence.
Which DI library works in commonMain for a KMP project?
Hilt and Dagger are Android/JVM-only and will not compile for iOS. Koin is the most common choice; add koin-core to commonMain and koin-android to androidMain, or use manual constructor injection.
What does the default hierarchy template do, and when should I add my own dependsOn?
Since Kotlin 1.9.20 the template auto-creates intermediate source sets like iosMain, appleMain, and nativeMain so you do not wire them by hand. If you add your own dependsOn calls the template switches off, so call applyDefaultHierarchyTemplate() explicitly when you only want to add an extra group.
How do you share a database across Android and iOS in KMP?
SQLDelight generates Kotlin from .sq files and each platform supplies its own SqlDriver (AndroidSqliteDriver vs NativeSqliteDriver). Room also supports KMP since 2.7; in both cases the repository lives in shared code and only the driver or builder is platform-specific.