Skip to content
Commitwise
Menu
Android Development

Kotlin Multiplatform for Android and iOS

Share business logic, networking and storage between Android and iOS with Kotlin Multiplatform, using source sets, expect and actual, Ktor and a multiplatform database, ship the shared code to Xcode, and handle the Swift interop details (suspend functions, Flows, exceptions, sealed classes) that decide whether iOS developers like it.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The Android and iOS apps of the recipe startup disagree. On Android, a shopping list merges duplicate ingredients; on iOS it doesn’t. Unit conversion rounds differently. The offline sync logic was written twice, by two people, and has two different bugs. Every new rule ships three weeks apart on the two platforms.

Kotlin Multiplatform (KMP)Kotlin MultiplatformKotlin technology for sharing code between Android, iOS and other platforms while keeping native apps and, optionally, native UI.Open in glossary → lets both apps share the code where they shouldn’t differ: models, business rules, networking, caching, sync. Each platform keeps its native UI (SwiftUI and Compose), or shares UI too with Compose Multiplatform. Google supports KMP for sharing business logic, and many large apps use it. The technology works; the hard parts are deciding what to share, and making the shared code pleasant to use from Swift.

New to some of these? Open what you need, or skip ahead.

Basics:What is a source set?

In a multiplatform module, code is organized in source sets: commonMain for code every platform uses, and androidMain, iosMain for platform-specific code. Common code can only use common libraries (no android.*, no UIKit). Each platform’s build combines commonMain with its own source set.

Basics:How does Swift call Kotlin?

Kotlin/Native compiles the shared module into an Apple framework, like any other library in Xcode. Swift imports it with import Shared and calls Kotlin classes and functions through the framework’s Objective-C header. That’s why some Kotlin features look different from Swift, as this lesson shows.

Part Not started

What to share and how

Think of the two apps as two restaurants with one central kitchen. The recipes (rules), the suppliers (network) and the pantry (storage) can be shared. The dining room, how food is served to guests, stays different in each restaurant: SwiftUI on iOS, Compose on Android.

A good first split:

  • Shared (commonMain): data classes, business rules (merge duplicate ingredients, convert units), repositories, API calls with Ktor, local storage with a multiplatform database, view-model-like state logic.
  • Native: screens and navigation, and things that are very different per platform, like push notification setup, payments, or camera access.

When shared code needs something platform-specific (the device name, a secure storage), there are two ways:

Share the layers with the most logic and the least platform coupling: domain models and rules, repositories, networking (Ktor with OkHttp/Darwin engines, kotlinx.serialization), persistence (SQLDelight, or Room’s KMP support, plus DataStore), sync and caching, and often presentation state (shared state holders or KMP-ready ViewModels exposing StateFlow). Keep UI native unless the team chooses Compose Multiplatform. Use expect/actual for small platform primitives (UUIDs, a logger, an engine factory) and interfaces injected from each platform for larger capabilities (secure storage, analytics, location), which keeps common code testable with fakes. Common code depends only on multiplatform libraries: kotlinx.coroutines, kotlinx.serialization, kotlinx-datetime, Koin or manual DI (Hilt is Android-only). Structure: one :shared umbrella module exported to iOS, depending on smaller KMP modules; the Android app consumes them as normal Gradle dependencies.

// shared/build.gradle.kts
kotlin {
    androidTarget()
    listOf(iosArm64(), iosSimulatorArm64()).forEach {
        it.binaries.framework {
            baseName = "Shared"
            isStatic = true
        }
    }
    sourceSets {
        commonMain.dependencies {
            implementation(libs.ktor.client.core)
            implementation(libs.ktor.client.content.negotiation)
            implementation(libs.ktor.serialization.kotlinx.json)
            implementation(libs.kotlinx.coroutines.core)
            implementation(libs.kotlinx.datetime)
        }
        androidMain.dependencies { implementation(libs.ktor.client.okhttp) }
        iosMain.dependencies { implementation(libs.ktor.client.darwin) }
        commonTest.dependencies { implementation(kotlin("test")) }
    }
}
// commonMain
expect fun httpEngine(): HttpClientEngine                 // each platform provides its engine

@Serializable
data class Ingredient(val name: String, val amount: Double, val unit: String)

object ShoppingList {
    /** The rule both apps disagreed on, now written once. */
    fun merge(items: List<Ingredient>): List<Ingredient> =
        items.groupBy { it.name.lowercase() to it.unit }
            .map { (_, same) -> same.first().copy(amount = same.sumOf { it.amount }) }
}

class RecipeRepository(private val baseUrl: String) {
    private val client = HttpClient(httpEngine()) {
        install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
    }

    suspend fun ingredients(recipeId: String): List<Ingredient> =
        client.get("$baseUrl/recipes/$recipeId/ingredients").body()
}

// androidMain
actual fun httpEngine(): HttpClientEngine = OkHttp.create()

// iosMain
actual fun httpEngine(): HttpClientEngine = Darwin.create()
  • androidTarget() and the iOS targets say which platforms to build for. The iOS ones produce a framework called Shared for Xcode.
  • commonMain.dependencies are libraries that work everywhere; each platform adds its own HTTP engine.
  • expect fun httpEngine() is a promise in common code; actual fun in each platform keeps it.
  • ShoppingList.merge is the business rule, now one function with one set of tests for both apps.

Predict the output

commonMain declares expect fun deviceName(): String. androidMain has the actual implementation, but iosMain doesn't. You build the Android app. Then you build the iOS framework. What happens?

Practice: test the shared rule once

Shared code means shared tests. A test in commonTest runs on the JVM and on iOS simulators.

// commonTest
class ShoppingListTest {
    @Test
    fun mergesSameIngredientAndUnit() {
        val merged = ShoppingList.merge(
            listOf(
                Ingredient("Flour", 200.0, "g"),
                Ingredient("flour", 300.0, "g"),
                Ingredient("Milk", 1.0, "l"),
            )
        )
        assertEquals(2, merged.size)
        assertEquals(500.0, merged.first { it.name.equals("flour", ignoreCase = true) }.amount)
    }

    @Test
    fun keepsDifferentUnitsApart() {
        val merged = ShoppingList.merge(listOf(Ingredient("Sugar", 100.0, "g"), Ingredient("Sugar", 1.0, "cup")))
        assertEquals(2, merged.size)
    }
}

./gradlew :shared:allTests runs them on every target. The bug where iOS didn’t merge “Flour” and “flour” can’t come back on either platform.

Adopting KMP in existing apps

  • Start small and real: one module with a contained, valuable piece (validation rules, a pricing engine, the sync engine), consumed by both apps behind the existing interfaces.
  • Ownership: shared code needs owners from both platforms; iOS engineers must be able to read, build and debug it (Xcode can step into Kotlin with the right plugin, and Android Studio and Fleet support iOS run configurations).
  • Costs: a Kotlin/Native build in the iOS pipeline (minutes, cache it), a bigger iOS binary (a few MB for the runtime and dependencies), and learning curves on both sides.
  • Distribution: a direct Gradle integration in a monorepo (embedAndSignAppleFrameworkForXcode build phase), or a versioned XCFramework published as a Swift package for separate repositories.
  • Share: models, rules, repositories, Ktor networking, SQLDelight/Room KMP/DataStore, sync, optionally presentation state. Keep UI native unless adopting Compose Multiplatform.
  • expect/actual for small primitives; injected interfaces for capabilities (testable, explicit).
  • Common code uses multiplatform libraries only: coroutines, serialization, datetime; Koin or manual DI.
  • Umbrella :shared module exported to iOS; tests in commonTest run per target.
  • Adoption: start with one valuable module, shared ownership, budget for Kotlin/Native build time and binary size; monorepo Gradle integration or XCFramework via SPM.

Check this part

  1. Which code is usually shared first with KMP?

  2. What does an actual declaration do?

  3. Shared code needs secure storage. Usually the more testable choice?

  4. Which DI approach works in common code?

Put models, business rules, repositories, networking (Ktor) and storage (SQLDelight or Room KMP, DataStore) in commonMain; keep UI and platform integrations native. expect/actual declares an API in common code and implements it per platform, but interfaces with platform implementations injected from each app are often simpler. Use Kotlin-first libraries (kotlinx.serialization, kotlinx.coroutines, kotlinx-datetime) in common code.

Part Not started

Making shared code nice to use from Swift

iOS developers will use the shared code every day, so how it looks in Swift matters as much as how it works. Swift sees it through an Objective-C bridge, which changes a few things:

  • suspend functions can be called with try await in Swift.
  • Errors: Kotlin doesn’t have checked exceptions. A Kotlin function that throws must say so with @Throws(…), otherwise the exception doesn’t become a Swift error: it crashes the app.
  • Flows (streams of values) have no direct Swift equivalent. Shared code needs a small wrapper, or a tool such as SKIE that turns them into Swift AsyncSequences.
  • Sealed classes become normal classes in Swift, so switch can’t check that every case is covered. SKIE fixes this too.

So the shared module’s public API should be designed for Swift users as well: few, clear entry points, errors declared, and streams exposed in a way Swift can consume.

The default export goes through Objective-C: classes become KotlinBase subclasses, generics on interfaces are lost (classes keep them in a limited form), default arguments disappear, top-level functions land on <File>Kt classes, and Int/Long map to Int32/Int64. Suspend functions are exported as completion-handler methods, which Swift imports as async (cancellation from Swift doesn’t propagate to the coroutine by default). Exceptions: only those listed in @Throws are translated to NSError; any other exception crossing the boundary (including from a suspend function, which implicitly declares only CancellationException) terminates the program. Annotate the exported API with @Throws(Exception::class) at boundaries or return a Result-like type. Flows have no ObjC mapping; options are a callback-based wrapper class, KMP-NativeCoroutines (generates Swift AsyncSequence/Combine adapters with cancellation) or Touchlab’s SKIE (a compiler plugin that also exports sealed classes as Swift enums with exhaustive switching, suspend functions with cancellation, default arguments and Flows as AsyncSequence). JetBrains’ Swift export (direct Kotlin-to-Swift, without Objective-C) is in progress and removes much of this over time. Keep the exported surface deliberate: an umbrella module that re-exports only facades, explicit names (@ObjCName), and KDoc that shows up in Xcode.

// iOS
import Shared

@Observable @MainActor
final class ShoppingListModel {
    private(set) var items: [Ingredient] = []
    private(set) var errorMessage: String?
    private let service: RecipeService
    private var favorites: Cancellable?

    init(service: RecipeService) { self.service = service }

    func load(recipeIDs: [String]) async {
        do {
            items = try await service.shoppingList(recipeIds: recipeIDs)   // Kotlin suspend → Swift async
        } catch {
            errorMessage = "Couldn’t load the shopping list."              // the declared IOException
        }
    }

    func startObservingFavorites() {
        favorites = service.observeFavorites { ids in print("favorites:", ids) }
    }

    func stop() { favorites?.cancel() }
}
// commonMain: the facade exported to iOS
class RecipeService(private val repository: RecipeRepository) {

    @Throws(IOException::class, CancellationException::class)     // becomes a Swift `throws`
    suspend fun shoppingList(recipeIds: List<String>): List<Ingredient> =
        ShoppingList.merge(recipeIds.flatMap { repository.ingredients(it) })

    /** For Swift without SKIE: a stream as a callback, with a handle to stop it. */
    fun observeFavorites(onChange: (List<String>) -> Unit): Cancellable {
        val job = scope.launch { repository.favorites().collect { onChange(it) } }
        return Cancellable { job.cancel() }
    }

    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
}

fun interface Cancellable { fun cancel() }
  • @Throws(IOException::class, …) makes the Kotlin function a Swift throws function, so a network error lands in Swift’s catch. Without it, the same error would crash the iOS app.
  • try await service.shoppingList(...) calls the Kotlin suspend function like any Swift async function.
  • observeFavorites turns a Flow into a callback plus a Cancellable to stop it, something Swift can use without extra tools.
  • Swift sees List<Ingredient> as [Ingredient] and String as String.

Production puzzles

Spot the bugA crash only on iOS

Tap the line with the bug.

class SyncService(private val api: SyncApi, private val db: LocalDb) {
    suspend fun syncNow(): SyncResult {
        val changes = db.pendingChanges()
        val response = api.push(changes)          // throws ResponseException on HTTP 4xx/5xx
        db.markSynced(response.acceptedIds)
        return SyncResult(response.acceptedIds.size)
    }
}

Predict the output

Shared code exposes sealed class LoadState { object Loading; data class Loaded(val items: List<Item>); data class Failed(val message: String) }. Without SKIE, a Swift developer writes switch onto it. What do they get?

Exercisehard

Decide what to share

A fitness app with mature native apps: Android (Compose, Room, Retrofit), iOS (SwiftUI, Core Data, URLSession). Planned features: offline workout logging with sync, a new training-plan engine with complex rules, and Apple Health / Health Connect integration. Leadership asks whether to adopt KMP. What do you recommend, and how would you roll it out?

›

Rank the features by how much logic must be identical on both platforms and how platform-specific they are.

SolutionTry it yourself first
  • Share the training-plan engine first: new code, pure logic, must be identical, easy to test in commonTest. Export a small facade with declared errors.
  • Then the sync engine: conflict rules must match; storage stays native at first (an interface for local persistence, implemented with Room and Core Data), the network layer moves to Ktor in the shared module.
  • Keep native: Apple Health and Health Connect (different APIs and permissions), UI, notifications. The shared code receives normalized data through interfaces.
  • Rollout: one umbrella :shared module in the monorepo; iOS consumes it through the Gradle build phase; SKIE for Flows and sealed classes; CI builds the framework with caching and runs common tests on both targets.
  • Measure: bugs that differ between platforms, time to ship a rule on both platforms, iOS build time and app size, and iOS developers’ feedback after the first quarter.
Exercisemedium

Make the API Swift-friendly

A shared function is suspend fun login(email: String, password: String): User, which throws InvalidCredentialsException for a wrong password and IOException without network. iOS developers report crashes on wrong passwords. Fix the Kotlin side so Swift can handle both cases.

›

Swift only sees errors the Kotlin function declares.

SolutionTry it yourself first

Declare the exceptions:

@Throws(InvalidCredentialsException::class, IOException::class, CancellationException::class)
suspend fun login(email: String, password: String): User

Swift can now write:

do {
    let user = try await auth.login(email: email, password: password)
    session.start(user)
} catch {
    errorMessage = "Wrong email or password, or no connection."
}

Or return a sealed LoginResult (Success(user), WrongPassword, Offline) instead of throwing, which makes each case explicit on both platforms.

  • Default export is via Objective-C: no default arguments, limited generics, <File>Kt for top-level functions, Int32/Int64 mappings.
  • Suspend → Swift async (no cancellation propagation by default). Only @Throws-declared exceptions become Swift errors; anything else crashes. Suspend functions implicitly declare only CancellationException.
  • Flows: callback wrappers, KMP-NativeCoroutines, or SKIE (AsyncSequence); SKIE also exports sealed classes as exhaustive Swift enums.
  • Swift export (direct, no ObjC) is in progress.
  • Curate the exported surface: facades, @ObjCName, KDoc, declared errors or result types.

Check this part

  1. A Kotlin function throws an exception not listed in @Throws, called from Swift. What happens?

  2. How does Swift call a Kotlin suspend function?

  3. What does SKIE add for Swift users?

  4. Why are exported sealed classes risky without SKIE?

Swift sees Kotlin through an Objective-C header. Suspend functions become async functions (or completion handlers); only exceptions declared with @Throws reach Swift as errors, and anything else crashes the app. Flows have no Swift equivalent: expose them through a wrapper or use SKIE or KMP-NativeCoroutines. Sealed classes and enums arrive as classes without exhaustive switching unless you use SKIE. Design the exported API for Swift: small, explicit, documented.

Key takeaways

  • Share logic that must be identical (rules, networking, storage); keep UI native.
  • expect/actual or injected interfaces connect common code to each platform.
  • Test shared code once in commonTest.
  • Declare exceptions with @Throws, and wrap Flows for Swift.
  • Start with one valuable module and shared ownership across platforms.
  • Use multiplatform libraries and injected interfaces to keep common code testable.
  • Design the exported API for Swift: facades, declared errors, SKIE or adapters for Flows and sealed types.
  • Budget for build pipeline, binary size and the learning curve, and measure the payoff.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.