Kotlin Multiplatform cheat sheet

Revise Kotlin Multiplatform: expect/actual, Koin DI, Ktor engines, Compose Multiplatform, and Swift interop for cross-platform Android and iOS apps.

Key ideas

  1. commonMain is the root source set; androidMain and iosMain are platform source sets created by the default hierarchy template (Kotlin 1.9.20+).
  2. Prefer an interface plus DI (Koin) for platform abstractions; keep expect/actual for small primitives like platform name or UUID.
  3. Ktor client uses OkHttp on Android and Darwin on iOS; ktor-client-core lives in commonMain, each engine in its platform source set.
  4. Hilt and Dagger are Android/JVM-only; use Koin or manual constructor injection in commonMain so shared code compiles for iOS.
  5. Kotlin/Native produces a .framework for Xcode; Swift sees suspend as completion handlers, but Flow needs SKIE or KMP-NativeCoroutines.
  6. Compose Multiplatform uses the same androidx.compose.* packages; iOS renders via Skia into a Metal layer, so text metrics differ from Android.
  7. A single Json { ignoreUnknownKeys = true } in commonMain prevents additive backend changes from breaking older clients on either platform.
  8. Building iOS targets requires a Mac with Xcode; CI for a KMP project needs a macOS runner.
  9. expect/actual classes are Beta in Kotlin 2.x; add -Xexpect-actual-classes to suppress the warning, but prefer interfaces instead.

APIs at a glance

API or termUse it for
kotlin("multiplatform")Gradle plugin applied to the shared module to enable KMP targets.
com.android.kotlin.multiplatform.libraryAndroid-KMP library plugin; replaces the older com.android.library + androidTarget() setup deprecated in AGP 9.
expect / actualCompile-time platform-specific declarations for small primitives; classes are Beta.
startKoin / moduleMultiplatform DI; single for app-wide objects, factory for per-screen, scopes for session state.
ktor-client-core / ktor-client-okhttp / ktor-client-darwinShared HTTP client in commonMain; per-platform engine in androidMain or iosMain.
@Serializable / kotlinx.serializationJSON (de)serialization in commonMain; pair with ContentNegotiation in the shared HttpClient.
binaries.frameworkProduces a .framework that Xcode links; dynamic by default, set isStatic = true if a dynamic one causes duplicate-symbol or linking errors.
ComposeUIViewControlleriOS entry point from androidx.compose.ui.window; wrap in UIViewControllerRepresentable for SwiftUI.
SKIE / KMP-NativeCoroutinesBridge Kotlin Flow to Swift AsyncSequence; neither ships with Compose Multiplatform.
@ThrowsPropagate a specific Kotlin exception to Swift as NSError; without it, a suspend function only propagates CancellationException.
@ObjCNameSet 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.systemVersion

Koin 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 commonMain plus DI over expect/actual for any platform abstraction larger than a one-line primitive.
  • Never import android.*, platform.Foundation, or java.* in commonMain; 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() and iosSimulatorArm64(); iosX64() is only for Intel Mac simulators and is being phased out.
  • Prefer a single Json { ignoreUnknownKeys = true } in commonMain so additive backend changes do not break older clients.
  • Never hand-collect a Flow in Swift; wrap it with SKIE or KMP-NativeCoroutines and tie collection to a cancellable Task.

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 commonTest awkward; use an interface in commonMain with DI instead.
  • Importing android.util.Log or Context in commonMain. commonMain cannot see Android APIs, so the code will not compile; define an interface in commonMain and implement it in androidMain and iosMain.
  • Declaring ktor-client-core in commonMain without an engine in a platform source set. HttpClient() has no engine at runtime and crashes; add ktor-client-okhttp to androidMain and ktor-client-darwin to iosMain.
  • 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 CancellationException propagates as NSError; 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.

Go deeper