首页 > 解决方案 > 如何修复 IntelliJ IDEA 中冲突的 Kotlin 依赖项?

问题描述

我们正在 Kotlin 中创建一个多平台项目,并且某个模块的一部分使用了实验性协程功能。

我们正在使用 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 无法识别它并显示未解决的引用错误:

未解决的参考错误,IntelliJ

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

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

IntelliJ 中的模块依赖关系

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

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

标签: gradlekotlindependencies

解决方案


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-commonkotlinx-coroutines依赖的,但仍添加kotlin-stdlib-common您指定的。


推荐阅读