简单介绍全栈 KMP,介绍 expect / actual

This commit is contained in:
SOR
2026-10-09 16:56:52 +08:00
parent 4a070e4253
commit 73d93f7bc8
4 changed files with 98 additions and 2 deletions
@@ -4,5 +4,73 @@
## expect / actual
这东西其实叫`预期与实际机制`,但是真的不好描述。
这东西其实叫`预期与实际机制`,但是真的不好描述,用法也比较多样。
### 推荐的写法
写一个文件 `xxx.kt`,里面定义一个函数,在其他平台的代码里也定义同样的文件,然后上一个后缀,例如 JVM 的 `xxx.jvm.kt`。
#### 顶层函数
创建一个新的 KMP 项目时,就会给一个 expect 函数的例子:
```kotlin
// commonMain
interface Platform { // 接口定义在 common 里
val name: String
}
expect fun getPlatform(): Platform
// jvmMain
class JVMPlatform: Platform { // 各平台有自己的实现
override val name: String = "Java ${System.getProperty("java.version")}"
}
actual fun getPlatform(): Platform = JVMPlatform()
// androidMain
class AndroidPlatform : Platform {
override val name: String = "Android ${Build.VERSION.SDK_INT}"
}
actual fun getPlatform(): Platform = AndroidPlatform()
```
#### 顶层变量
这个应用的情况会比较少。
```kotlin
// commonMain
expect val isDebugMode: Boolean
// androidMain
actual val isDebugMode: Boolean = BuildConfig.DEBUG
// iosMain
actual val isDebugMode: Boolean = Platform.isDebugBinary
```
### 在实验中 / 不稳定的写法(截至20261009)
各种类定义也是可以用 expect / actual 的。这里用普通类举例子:
```kotlin
// commonMain
expect class DeviceIdProvider() {
fun getUniqueId(): String
}
// androidMain
actual class DeviceIdProvider actual constructor() {
actual fun getUniqueId(): String = Settings.Secure.getString(...)
}
```
## 接下来可以看
[目录](../README.md)
[下一篇:全栈 KMP](./全栈KMP.md)