跨平台开发 (KMP)
KMP 的核心愿景是:共享逻辑,保留原生体验。这与 Flutter 的“自带渲染引擎”路线完全不同。
快速上手 (Gradle 配置)
在 shared 模块中配置 KMP 插件及源集(Source Sets):
kotlin
plugins {
kotlin("multiplatform")
}
kotlin {
// 目标平台
androidTarget()
iosSimulatorArm64()
iosArm64()
sourceSets {
commonMain.dependencies {
// 共享库依赖
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}
androidMain.dependencies {
// Android 特有依赖
}
iosMain.dependencies {
// iOS 特有依赖
}
}
}编译契约:expect / actual
这是 KMP 的魔法核心。
commonMain: 定义expect规则。androidMain/iosMain: 提供actual实现。
kotlin
// commonMain
expect fun getPlatformName(): String
// androidMain
actual fun getPlatformName(): String = "Android ${Build.VERSION.SDK_INT}"
// iosMain
actual fun getPlatformName(): String = UIDevice.currentDevice.systemName() +
" " +
UIDevice.currentDevice.systemVersion内存管理革命 (New Memory Manager)
在 Kotlin 1.9 之前,Native 端的对象模型非常痛苦(需要 freeze() 冻结对象才能跨线程)。 现状:现代 KMP 默认启用了新内存管理器。
- 完全线程共享: 不再需要
freeze()。 - 泄漏检测: 提供了类似 Java 的垃圾回收体验。
架构分层
mermaid
graph TD
Common[commonMain] --> Apple[appleMain (Shared iOS/macOS)]
Common --> Android[androidMain]
Apple --> iOS[iosMain]
Apple --> Mac[macosMain]通过中间层 appleMain,你可以编写一次代码,同时运行在 iPhone 和 MacBook 上,极大复用了 Apple 生态的逻辑。