如何在IntelliJ IDEA中解决Kotlin依赖冲突?

5
我们正在使用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无法识别它并显示“未解决的引用”错误: Unresolved reference error, IntelliJ 这变得非常烦人,因为几乎所有文件都被标记为包含致命错误,即使您可以毫无问题地构建它们。
在检查模块依赖项时,我发现IntelliJ确实认为该模块依赖于两个Kotlin标准库: Module dependencies in IntelliJ 我发现如果我从此列表中删除kotlin-stdlib-1.2.21依赖项,则IntelliJ将停止显示“未解决的引用”错误。不幸的是,在使用Gradle重新同步项目后,依赖关系会恢复。
有没有办法避免这个问题?
1个回答

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

这将从m的依赖中排除模块x,但如果您依赖于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


太棒了!非常感谢。那真的帮了我很多。不幸的是,我无法为您的答案点赞,对此感到抱歉。 - Andrew
那不重要,我很高兴能帮助你 :) - ice1000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接