簡體   English   中英

Kotlin Multiplatform:無法從另一個模塊的 androidMain 源集中引用 commonMain 源集中的類

[英]Kotlin Multiplatform: Can't reference class in commonMain sourceset from another module's androidMain sourceset

我在一個針對 Android 和 iOS 的標准多平台模板項目中shared了兩個多平台模塊和other模塊。

sharedcommonMain源集中定義了一個類

class SharedGreeting()

other設置為依賴於 gradle 文件中這樣的shared

val commonMain by getting {
            dependencies {
                implementation(project(":shared"))
            }
        }

在其androidMain ,它嘗試在某些類 fx 中引用SharedGreeting

class AndroidGreeter{
   val foo = SharedGreeting()
}

但是無論我嘗試什么,當我嘗試引用共享類時都會出現 IDE 錯誤,並且我必須手動添加導入語句。

代碼編譯和部署沒有問題! 關於我遺漏或誤解的任何想法? 還是這是 KMM 中的錯誤?

other gradle 文件的完整副本:

plugins {
    kotlin("multiplatform")
    kotlin("native.cocoapods")
    id("com.android.library")
}

version = "1.0"

kotlin {
    android()
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    cocoapods {
        summary = "Some description for the Shared Module"
        homepage = "Link to the Shared Module homepage"
        ios.deploymentTarget = "14.1"
        framework {
            baseName = "other"
        }
    }
    
    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation(project(":shared"))
            }
        }
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test"))
            }
        }
        val androidMain by getting
        val androidTest by getting
        val iosX64Main by getting
        val iosArm64Main by getting
        val iosSimulatorArm64Main by getting
        val iosMain by creating {
            dependsOn(commonMain)
            iosX64Main.dependsOn(this)
            iosArm64Main.dependsOn(this)
            iosSimulatorArm64Main.dependsOn(this)
        }
        val iosX64Test by getting
        val iosArm64Test by getting
        val iosSimulatorArm64Test by getting
        val iosTest by creating {
            dependsOn(commonTest)
            iosX64Test.dependsOn(this)
            iosArm64Test.dependsOn(this)
            iosSimulatorArm64Test.dependsOn(this)
        }
    }
}

android {
    compileSdk = 32
    sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
    defaultConfig {
        minSdk = 24
        targetSdk = 32
    }
}

完整的項目源代碼: https ://github.com/RabieJradi/kmm_import_error_sample

不幸的是,IDE 建議的添加依賴項的操作沒有做任何事情。 在此處輸入圖像描述

你不能那樣做。

為了使您的項目工作,您必須使用期望實際的單詞。

因此,進行以下更改:

像這樣更改共享模塊中的SharedGreeting類:

expect class SharedGreeting {
    fun greeting(): String
}

然后您的 IDE 希望您在共享模塊中進行兩項更改。 iosMainandroidMain這兩個模塊中添加一個名為SharedGreeting的類。 兩個類的代碼相同:

actual class SharedGreeting {
    actual fun greeting(): String {
        return "Hello, ${Platform().platform}!"
    }
}

工作完成,現在您的其他庫沒有錯誤。 從“其他”中的 androidMain 模塊中,您只能在其他 MKK 庫中的其他 androidMain 模塊上工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM