KMM Kotlin expect的几种声明方式
前言
Kotlin的expect關鍵字一般用在多平臺上,比如在多平臺項目中的common中聲明方法簽名,然后由不同的平臺去實現該方法,從而實現一個多平臺(跨平臺)方法.
創建KMM項目可以參考:?KMM(二)+Compose(二) 開發一個Kotlin多平臺應用_滔lt的博客-CSDN博客
正文
接下來就說一下Kotlin expect的幾種聲明方式
1.頂層函數和頂層擴展函數
在commonMain文件夾中聲明:
在androidMain(和其他平臺)文件夾中實現:
聲明并實現后,不管是共享代碼還是平臺代碼中都可以使用相應方法
2.屬性
?聲明:
expect val isDebug: Boolean?實現:
actual val isDebug: Boolean = BuildConfig.DEBUG3.注解
聲明:
@Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) internal expect annotation class ExpectAnnotation()實現:
@Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) internal actual annotation class ExpectAnnotation()4.枚舉
聲明:
expect enum class Enum實現:
actual enum class Enum {enum1,enum2,enum3, }5.接口
聲明:
expect interface Interface {fun fun1()fun fun2(): String }實現:
actual interface Interface {actual fun fun1()actual fun fun2(): Stringfun fun3() {"fun3".loge()} }6.類
聲明:
expect class Class() {fun fun1()fun fun2(): String }實現:
actual class Class {actual fun fun1() {}actual fun fun2(): String {return getUUID()} }經測試,sealed class可以,data class好像用不了
ps:在公共模塊使用接口和類暫時需要手動導包
7.typealias
使用kotlin的typealias特性,我們可以將一個已經實現類映射為expect的實現
我們接下來實現一個多平臺的ViewModel
先去common目錄下的build.gradle.kts文件中
添加viewmodel的依賴:
val androidMain by getting {dependencies {api("androidx.appcompat:appcompat:1.2.0")api("androidx.core:core-ktx:1.3.1")api("androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1")//增加vm依賴}}聲明:
expect open class MViewModel() {protected open fun onCleared() }androidMain實現(直接使用ViewModel):
import androidx.lifecycle.ViewModelopen class MyViewModel : ViewModel() {override fun onCleared() {super.onCleared()} }actual typealias MViewModel = MyViewModelps:這里說一下為什么要實現一下ViewModel才使用?typealias,首先ViewModel是個抽象類,但又沒必要搞成抽象的,最重要的是Kotlin的protected和Java的protected可見性不同,所以導致typealias無法直接匹配上,不知道Kotlin后續要怎么補上這個坑,參考下圖和文章:
學習Kotlin(三)類和接口_滔lt的博客-CSDN博客
desktopMain實現:?
actual open class MViewModel {protected actual open fun onCleared() {} }上面代碼放在了Github的expects目錄:?ltttttttttttt/KMM_and_Compose_Sample
參考Kotlin官網:?Connect to platform-specific APIs | Kotlin
如有錯誤歡迎大佬們指出
end
總結
以上是生活随笔為你收集整理的KMM Kotlin expect的几种声明方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: KMM+Compose 开发一个Kotl
- 下一篇: 安卓使用Span富文本给某段Text文本