mcpField
K
kmp

kmp

github.com/andvl1开发579 次安装15 周前更新
代码仓库

关于 kmp

面向 Kotlin Multiplatform 开发者的实践指南,介绍 Android、iOS、Desktop、Web(WASM)和 Server 的共享代码项目结构与实现模式,涵盖模块划分、平台代码、测试及目标平台限制。

主要功能

  1. 01多模块项目组织
  2. 02源集与目标配置
  3. 03expect/actual 平台实现
  4. 04共享及平台专属测试
  5. 05WASM 限制与存储模式

适用场景

  1. 01规划 KMP 项目模块结构
  2. 02实现平台专属 API
  3. 03测试共享 Kotlin 代码
  4. 04适配 WASM 存储与网络

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/andvl1/claude-plugin --skill kmp

安装后在 Claude Code 中输入/kmp确认已加载。

详细介绍

Kotlin Multiplatform(KMP)基础知识

Kotlin Multiplatform 支持在 Android、iOS、桌面端、Web(WASM)和服务端之间共享代码。

项目结构

多模块架构(按功能划分 + api/impl)
your-project-admin/
├── build.gradle.kts              # Root build config
├── settings.gradle.kts           # Module includes
├── gradle/libs.versions.toml     # Version catalog
│
├── core/
│   ├── common/                   # Utilities, Result types, extensions
│   │   └── src/commonMain/kotlin/
│   ├── data/                     # Data abstractions, DataStore
│   │   ├── src/commonMain/kotlin/
│   │   ├── src/androidMain/kotlin/
│   │   └── src/iosMain/kotlin/
│   ├── database/                 # Room (Android/iOS/JVM only)
│   │   └── src/commonMain/kotlin/
│   ├── network/                  # Ktor client
│   │   └── src/commonMain/kotlin/
│   └── ui/                       # Design system, theme
│       └── src/commonMain/kotlin/
│
├── feature/
│   ├── auth/
│   │   ├── api/                  # Public interfaces, models
│   │   │   └── src/commonMain/kotlin/
│   │   └── impl/                 # Implementation, UI
│   │       └── src/commonMain/kotlin/
│   └── home/
│       ├── api/
│       └── impl/
│
├── composeApp/                   # Platform entry points
│   ├── src/commonMain/           # App composition, DI graph
│   ├── src/androidMain/          # MainActivity
│   ├── src/iosMain/              # iOS entry
│   ├── src/jvmMain/              # Desktop main()
│   └── src/wasmJsMain/           # Web entry
│
└── iosApp/                       # Xcode project
源集层次结构
commonMain
├── androidMain
├── iosMain
│   ├── iosX64Main
│   ├── iosArm64Main
│   └── iosSimulatorArm64Main
├── jvmMain
├── wasmJsMain
└── jsMain (fallback)

Gradle 设置

根目录 build.gradle.kts
plugins {
    alias(libs.plugins.kotlinMultiplatform) apply false
    alias(libs.plugins.androidApplication) apply false
    alias(libs.plugins.androidLibrary) apply false
    alias(libs.plugins.composeMultiplatform) apply false
    alias(libs.plugins.composeCompiler) apply false
    alias(libs.plugins.kotlinSerialization) apply false
    alias(libs.plugins.ksp) apply false
    alias(libs.plugins.room) apply false
    alias(libs.plugins.metro) apply false
}
settings.gradle.kts
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "your-project-admin"

// Core modules
include(":core:common")
include(":core:data")
include(":core:database")
include(":core:network")
include(":core:ui")

// Feature modules
include(":feature:auth:api")
include(":feature:auth:impl")
include(":feature:home:api")
include(":feature:home:impl")

// App entry points
include(":composeApp")
gradle/libs.versions.toml
[versions]
kotlin = "2.3.20"
agp = "9.1.0"
compose-multiplatform = "1.10.3"
ktor = "3.4.1"
room = "2.8.4"
datastore = "1.2.0"
decompose = "3.5.0"
metro = "0.10.2"
essenty = "2.5.0"
coroutines = "1.10.2"
serialization = "1.10.0"
ksp = "2.3.20-1.0.31"

[libraries]
# Kotlin
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }

# Ktor
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }

# Room (Android, iOS, JVM only)
androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "room" }
androidx-room-compiler = { module = "androidx.room:room-compiler", version.ref = "room" }
androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version = "2.6.2" }

# DataStore
datastore-preferences-core = { module = "androidx.datastore:datastore-preferences-core", version.ref = "datastore" }

# Decompose
decompose = { module = "com.arkivanov.decompose:decompose", version.ref = "decompose" }
decompose-compose = { module = "com.arkivanov.decompose:extensions-compose", version.ref = "decompose" }
essenty-lifecycle = { module = "com.arkivanov.essenty:lifecycle", version.ref = "essenty" }

[plugins]
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
androidApplication = { id = "com.android.application", version.ref = "agp" }
androidLibrary = { id = "com.android.library", version.ref = "agp" }
composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "compose-multiplatform" }
composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
room = { id = "androidx.room", version.ref = "room" }
metro = { id = "dev.zacsweers.metro", version.ref = "metro" }
模块 build.gradle.kts(KMP 库)
// core/common/build.gradle.kts
plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.androidLibrary)
}

kotlin {
    androidTarget {
        compilerOptions {
            jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21)
        }
    }

    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "CoreCommon"
            isStatic = true
        }
    }

    jvm("desktop")

    wasmJs {
        browser()
    }

    sourceSets {
        commonMain.dependencies {
            implementation(libs.kotlinx.coroutines.core)
        }

        androidMain.dependencies {
            // Android-specific
        }

        iosMain.dependencies {
            // iOS-specific
        }

        val desktopMain by getting {
            dependencies {
                // Desktop-specific
            }
        }
    }
}

android {
    namespace = "com.your-project.admin.core.common"
    compileSdk = 35

    defaultConfig {
        minSdk = 24
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_21
        targetCompatibility = JavaVersion.VERSION_21
    }
}

expect/actual 模式

声明(commonMain)
// commonMain/kotlin/Platform.kt
expect class PlatformContext

expect fun getPlatformName(): String

expect fun createDataStorePath(context: PlatformContext): String
Android 实现
// androidMain/kotlin/Platform.android.kt
actual typealias PlatformContext = android.content.Context

actual fun getPlatformName(): String = "Android ${android.os.Build.VERSION.SDK_INT}"

actual fun createDataStorePath(context: PlatformContext): String {
    return context.filesDir.resolve("datastore").absolutePath
}
iOS 实现
// iosMain/kotlin/Platform.ios.kt
import platform.Foundation.NSDocumentDirectory
import platform.Foundation.NSFileManager
import platform.Foundation.NSUserDomainMask

actual class PlatformContext

actual fun getPlatformName(): String = "iOS"

actual fun createDataStorePath(context: PlatformContext): String {
    val documentDir = NSFileManager.defaultManager.URLForDirectory(
        NSDocumentDirectory,
        NSUserDomainMask,
        null,
        false,
        null
    )
    return "${documentDir?.path}/datastore"
}
桌面端实现
// desktopMain/kotlin/Platform.jvm.kt
import java.io.File

actual class PlatformContext

actual fun getPlatformName(): String =
    "${System.getProperty("os.name")} ${System.getProperty("os.version")}"

actual fun createDataStorePath(context: PlatformContext): String {
    val home = System.getProperty("user.home")
    return File(home, ".your-project-admin/datastore").absolutePath
}
WASM 实现
// wasmJsMain/kotlin/Platform.wasmJs.kt
actual class PlatformContext

actual fun getPlatformName(): String = "Web (WASM)"

actual fun createDataStorePath(context: PlatformContext): String {
    return "your-project-admin-datastore"  // Uses localStorage
}

模块依赖

依赖规则
composeApp
├── feature:auth:impl
│   ├── feature:auth:api
│   ├── core:ui
│   └── core:network
├── feature:home:impl
│   ├── feature:home:api
│   ├── core:ui
│   └── core:database
├── core:ui
│   └── core:common
├── core:network
│   └── core:common
├── core:database
│   └── core:common
└── core:data
    └── core:common
api/impl 模式
// feature/auth/api/build.gradle.kts
plugins {
    alias(libs.plugins.kotlinMultiplatform)
}

kotlin {
    // Targets...

    sourceSets {
        commonMain.dependencies {
            // Only models and interfaces - no implementations
            api(projects.core.common)
        }
    }
}

// feature/auth/impl/build.gradle.kts
plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.composeMultiplatform)
    alias(libs.plugins.composeCompiler)
}

kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation(projects.feature.auth.api)
            implementation(projects.core.ui)
            implementation(projects.core.network)
            implementation(libs.decompose)
            implementation(libs.decompose.compose)
        }
    }
}

常见模式

Result 类型
// core/common/src/commonMain/kotlin/Result.kt
sealed class AppResult<out T> {
    data class Success<T>(val data: T) : AppResult<T>()
    data class Error(val message: String, val cause: Throwable? = null) : AppResult<Nothing>()
    data object Loading : AppResult<Nothing>()
}

inline fun <T, R> AppResult<T>.map(transform: (T) -> R): AppResult<R> = when (this) {
    is AppResult.Success -> AppResult.Success(transform(data))
    is AppResult.Error -> this
    is AppResult.Loading -> this
}

inline fun <T> AppResult<T>.onSuccess(action: (T) -> Unit): AppResult<T> {
    if (this is AppResult.Success) action(data)
    return this
}

inline fun <T> AppResult<T>.onError(action: (String, Throwable?) -> Unit): AppResult<T> {
    if (this is AppResult.Error) action(message, cause)
    return this
}
Repository 接口(api 模块)
// feature/auth/api/src/commonMain/kotlin/AuthRepository.kt
interface AuthRepository {
    suspend fun login(email: String, password: String): AppResult<User>
    suspend fun logout(): AppResult<Unit>
    fun observeAuthState(): Flow<AuthState>
}

data class User(
    val id: String,
    val email: String,
    val name: String
)

sealed class AuthState {
    data object Unauthenticated : AuthState()
    data class Authenticated(val user: User) : AuthState()
}
Repository 实现(impl 模块)
// feature/auth/impl/src/commonMain/kotlin/AuthRepositoryImpl.kt
class AuthRepositoryImpl(
    private val apiService: AuthApiService,
    private val tokenStorage: TokenStorage
) : AuthRepository {

    private val _authState = MutableStateFlow<AuthState>(AuthState.Unauthenticated)

    override suspend fun login(email: String, password: String): AppResult<User> {
        return try {
            val response = apiService.login(LoginRequest(email, password))
            tokenStorage.saveToken(response.token)
            _authState.value = AuthState.Authenticated(response.user)
            AppResult.Success(response.user)
        } catch (e: Exception) {
            AppResult.Error("Login failed: ${e.message}", e)
        }
    }

    override suspend fun logout(): AppResult<Unit> {
        tokenStorage.clearToken()
        _authState.value = AuthState.Unauthenticated
        return AppResult.Success(Unit)
    }

    override fun observeAuthState(): Flow<AuthState> = _authState.asStateFlow()
}

运行时平台检查

// When expect/actual is overkill, use runtime checks
enum class Platform {
    Android, iOS, Desktop, Web
}

expect val currentPlatform: Platform

// androidMain
actual val currentPlatform: Platform = Platform.Android

// iosMain
actual val currentPlatform: Platform = Platform.iOS

// desktopMain
actual val currentPlatform: Platform = Platform.Desktop

// wasmJsMain
actual val currentPlatform: Platform = Platform.Web

// Usage
@Composable
fun AdaptiveComponent() {
    when (currentPlatform) {
        Platform.Android -> AndroidSpecificUI()
        Platform.iOS -> IOSSpecificUI()
        Platform.Desktop -> DesktopSpecificUI()
        Platform.Web -> WebSpecificUI()
    }
}

测试

共享测试(commonTest)
// core/common/src/commonTest/kotlin/ResultTest.kt
class ResultTest {
    @Test
    fun `map transforms success value`() {
        val result: AppResult<Int> = AppResult.Success(5)
        val mapped = result.map { it * 2 }

        assertTrue(mapped is AppResult.Success)
        assertEquals(10, (mapped as AppResult.Success).data)
    }

    @Test
    fun `map preserves error`() {
        val result: AppResult<Int> = AppResult.Error("test error")
        val mapped = result.map { it * 2 }

        assertTrue(mapped is AppResult.Error)
    }
}
平台专属测试
// androidTest - uses Robolectric or instrumented tests
// iosTest - runs on simulator
// jvmTest - standard JUnit

最佳实践

推荐做法
  • 尽可能将代码放在 commonMain 中
  • 仅将 expect/actual 用于平台 API
  • 尽量精简平台专属实现
  • 使用依赖注入处理平台差异
  • 在 commonTest 中测试共享代码
  • 使用版本目录管理依赖
不推荐做法
  • 不要将平台专属代码放入通用模块
  • 不要在不同平台源集中重复代码
  • 不要在公共 API 中使用平台专属类型
  • 不要跳过规范的模块拆分(api/impl)
  • 不要忽略数据库在 WASM 上的限制

WASM 限制

面向 WebAssembly 时的重要限制:

数据库
  • Room:不支持 WASM
  • 通过 expect/actual 模式使用 localStorage 或 IndexedDB
  • 考虑在 wasmJsMain 源集中跳过数据库
// commonMain - interface only
expect class AppStorage {
    fun getString(key: String): String?
    fun putString(key: String, value: String)
}

// wasmJsMain - browser storage
actual class AppStorage {
    actual fun getString(key: String): String? =
        window.localStorage.getItem(key)
    actual fun putString(key: String, value: String) {
        window.localStorage.setItem(key, value)
    }
}
网络
  • CORS:所有 HTTP 请求都受浏览器 CORS 策略约束
  • WebSocket:可以使用,但需要支持 CORS 的服务端
文件系统
  • 无法直接访问文件系统
  • 使用虚拟文件 API 或 blob URL
线程处理
  • 没有 Dispatchers.IO(请使用 Dispatchers.Default)
  • 可使用 Web Workers 执行后台任务(功能有限)

相关技能

  • kotlin-web — 基于 Kotlin 的 Web 前端(Compose WASM、Kotlin/JS+React、Kotlin/JS+Vue)。用于基本设置之外的 wasmJsMain 和 jsMain Web 模式。
  • kmp-feature-slice — 流程化的功能生成工作流。使用此技能的项目结构。
  • compose-arch — Compose UI 层的架构规则。

资源

评论

支持 Markdown