代码之家  ›  专栏  ›  技术社区  ›  Andrew

如何修复IntelliJ IDEA中冲突的Kotlin依赖关系?

  •  5
  • Andrew  · 技术社区  · 6 年前

    我们正在Kotlin创建一个多平台项目,某个模块的一部分使用了实验 coroutines 特色

    我们正在使用Gradle一起构建项目/库。通用模块的gradle构建脚本如下所示:

    apply plugin: 'kotlin-platform-common'
    
    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version"
        implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5"
        testCompile "org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlin_version"
        testCompile "org.jetbrains.kotlin:kotlin-test-common:$kotlin_version"
    }
    kotlin {
        experimental {
            coroutines "enable"
        }
    }
    

    这里真的没什么特别的。然而,协作程序所依赖的Kotlin标准库版本与我们希望在项目中使用的Kotlin标准库版本之间似乎存在冲突。

    除其他信息外 gradle module:dependencies 输出包含以下信息的树:

    compileClasspath - Compile classpath for source set 'main'.
    +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.2.41
    \--- org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5
         \--- org.jetbrains.kotlin:kotlin-stdlib:1.2.21
              \--- org.jetbrains:annotations:13.0
    
    compileOnly - Compile only dependencies for source set 'main'.
    No dependencies
    
    default - Configuration for default artifacts.
    +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.2.41
    \--- org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5
         \--- org.jetbrains.kotlin:kotlin-stdlib:1.2.21
              \--- org.jetbrains:annotations:13.0
    
    implementation - Implementation only dependencies for source set 'main'. (n)
    +--- org.jetbrains.kotlin:kotlin-stdlib-common:1.2.41 (n)
    \--- org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5 (n)
    

    如您所见,该项目依赖于Kotlin的版本1.2.41,但协同程序库内部依赖于1.2.21。

    这导致的问题是,当我使用Kotlin语言中的某些结构时,IntelliJ无法识别它,并显示 未解析的引用 错误:

    Unresolved reference error, IntelliJ

    这变得非常恼人,因为几乎所有文件都被IntelliJ标记为包含致命错误,即使您可以毫无问题地构建它们。

    在检查模块依赖关系后,我发现IntelliJ确实认为模块依赖于两个Kotlin标准库:

    Module dependencies in IntelliJ

    我发现如果我删除 kotlin-stdlib-1.2.21 从该列表中,IntelliJ将停止显示 未解析的引用 错误不幸的是,在使用Gradle重新同步项目时,依赖关系又回来了。

    有没有办法绕过这个问题?

    1 回复  |  直到 6 年前
        1
  •  8
  •   ice1000    6 年前

    如中所述 https://discuss.gradle.org/t/how-do-i-exclude-specific-transitive-dependencies-of-something-i-depend-on/17991 ,可以使用以下代码排除特定依赖项:

    compile('com.example.m:m:1.0') {
       exclude group: 'org.unwanted', module: 'x'
    }
    compile 'com.example.l:1.0'
    

    这将排除模块 x 从的依赖项 m ,但如果您依赖 l

    在你的情况下

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5") {
      exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib-common'
    }
    

    将阻止gradle加载 kotlin-stdlib-common 依赖于 kotlinx-coroutines 作为依赖项,但仍添加 kotlin stdlib通用 您指定了。