| name | android-kmp-shared-module |
| description | KMP shared module setup — expect/actual, commonMain/androidMain/iosMain source sets, what belongs in shared vs platform. Use when adding KMP support, creating a shared module, splitting Android code for multiplatform, or working with expect/actual declarations. Trigger on: "KMP", "multiplatform", "shared module", "commonMain", "expect/actual", "iOS shared", "kotlin multiplatform".
|
KMP Shared Module
Gradle setup (build.gradle.kts)
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidLibrary)
}
kotlin {
androidTarget {
compilations.all { kotlinOptions { jvmTarget = "11" } }
}
iosX64(); iosArm64(); iosSimulatorArm64()
sourceSets {
commonMain.dependencies {
implementation(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.serialization.json)
implementation(libs.ktor.client.core)
}
androidMain.dependencies {
implementation(libs.ktor.client.okhttp)
}
iosMain.dependencies {
implementation(libs.ktor.client.darwin)
}
}
}
android {
namespace = "com.example.shared"
compileSdk = libs.versions.compileSdk.get().toInt()
}
What belongs in commonMain
| Put in shared | Keep platform-specific |
|---|
| Domain models | Android Context usage |
| Repository interfaces | Room / SQLDelight Android config |
| Use cases | Compose UI |
| Ktor HTTP client calls | Android permissions |
kotlinx.serialization DTOs | Platform file paths |
kotlinx.coroutines flows | Firebase (Android only) |
| Feature flag interfaces | Play Billing |
expect / actual pattern
expect class PlatformInfo() {
val name: String
}
actual class PlatformInfo actual constructor() {
actual val name: String = "Android ${android.os.Build.VERSION.SDK_INT}"
}
actual class PlatformInfo actual constructor() {
actual val name: String = UIDevice.currentDevice.systemName()
}
Repository interface in shared, impl per platform
interface TaskRepository {
fun getTasks(): Flow<List<Task>>
suspend fun syncTasks(): EmptyResult<DataError>
}
class TaskRepositoryImpl(
private val dao: TaskDao,
private val api: TaskApi,
) : TaskRepository { ... }
Checklist