简单介绍全栈 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
+26
View File
@@ -0,0 +1,26 @@
# 全栈 KMP
**全栈**指:同时完成后端服务器的部分和前端用户的部分。
## 一个完整的 KMP 项目
目前(20261009),完整的 KMP 项目包含以下几项:
- Android
- JVM
- iOS
- WASM
- Server
除了 iOS 部分必须由 Xcode 做额外设置后编译以外,其他的应用均可在 JDK 下完成编译。
Server 本身也是运行在 JVM 上面的,它和普通的 Java / Kotlin 后端项目基本没有区别。不过,在 KMP 中,将它的部分代码写在 commonMain 中,可以在一定程度上减少代码的出错可能,还可以进行代码复用。
我们在编写全栈 KMP 时,应当优先考虑 WASM 和 Server 能否完美运行。
## 接下来可以看
[目录](../README.md)
[下一篇:复杂逻辑与多平台不同逻辑](./复杂逻辑与多平台不同逻辑.md)
[下一篇:编写服务器应用 —— SpringBoot](./Kotlin-Springboot.md)
@@ -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)
+2
View File
@@ -214,4 +214,6 @@ compose.desktop {
[下一篇:复杂逻辑与多平台不同逻辑](./复杂逻辑与多平台不同逻辑.md)
[下一篇:全栈 KMP](./全栈KMP.md)
[尝试完成2026年国庆小项目](https://git.itouc.cn/ITStudio_OUC/KMP_2026_National_Day_Project)
+1 -1
View File
@@ -16,7 +16,7 @@
1. [进入 KMP](learning/进入KMP.md)
2. [第一个 KMP 应用](Learning/第一个KMP应用.md)
3. [复杂逻辑与 expect / actual](Learning/复杂逻辑与多平台不同逻辑.md)
4.
4. [全栈 KMP](Learning/全栈KMP.md)
### Extra