如何修复 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 重新同步项目时,依赖项又回来了。

有没有办法规避这个问题?

如 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'

这会将模块xm的依赖项中排除,但如果您依赖于l,它仍然会带来它。

在您的情况下,只需

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

将阻止 gradle 将kotlinx-coroutines依赖kotlin-stdlib-common加载为依赖项,但仍添加您指定的kotlin-stdlib-common

最新更新