1.7 KiB
1.7 KiB
复杂逻辑与 expect / actual
确保你有至少看过一遍 深入 Kotlin
expect / actual
这东西其实叫预期与实际机制,但是真的不好描述,用法也比较多样。
推荐的写法
写一个文件 xxx.kt,里面定义一个函数,在其他平台的代码里也定义同样的文件,然后上一个后缀,例如 JVM 的 xxx.jvm.kt。
顶层函数
创建一个新的 KMP 项目时,就会给一个 expect 函数的例子:
// 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()
顶层变量
这个应用的情况会比较少。
// commonMain
expect val isDebugMode: Boolean
// androidMain
actual val isDebugMode: Boolean = BuildConfig.DEBUG
// iosMain
actual val isDebugMode: Boolean = Platform.isDebugBinary
在实验中 / 不稳定的写法(截至20261009)
各种类定义也是可以用 expect / actual 的。这里用普通类举例子:
// commonMain
expect class DeviceIdProvider() {
fun getUniqueId(): String
}
// androidMain
actual class DeviceIdProvider actual constructor() {
actual fun getUniqueId(): String = Settings.Secure.getString(...)
}