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:
- expect / actualexpect and actual (Kotlin Multiplatform)A Kotlin Multiplatform mechanism: common code declares an API with expect, and each platform provides it with actual.Open in glossary →: declare a function or class in common code with
expect, and write theactualversion inandroidMainandiosMain. - An interface: declare an interface in common code, implement it in each app, and pass it in. Often simpler and easier to test.
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 calledSharedfor Xcode.commonMain.dependenciesare libraries that work everywhere; each platform adds its own HTTP engine.expect fun httpEngine()is a promise in common code;actual funin each platform keeps it.ShoppingList.mergeis 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?
Every expect needs an actual for each target that compiles the common code. The Android compilation has one, so it succeeds; compiling for an iOS target fails with an error that the expected declaration has no actual. (The IDE also flags it in common code.) That's one reason interfaces implemented by each app can be easier: a missing implementation is a normal compile error in the app that forgot it.
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 (
embedAndSignAppleFrameworkForXcodebuild 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/actualfor small primitives; injected interfaces for capabilities (testable, explicit).- Common code uses multiplatform libraries only: coroutines, serialization, datetime; Koin or manual DI.
- Umbrella
:sharedmodule exported to iOS; tests incommonTestrun 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
Which code is usually shared first with KMP?
What does an actual declaration do?
Shared code needs secure storage. Usually the more testable choice?
Which DI approach works in common code?