在buildSrc中使用Firestore时遇到Kotlin版本依赖不兼容问题
Kotlin版本不兼容问题:buildSrc中引入Firebase依赖编译报错
环境配置
项目根build.gradle中使用的Kotlin Gradle插件版本:
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.20")
问题描述
在普通模块的build.gradle中引入Firebase相关代码可正常编译,但在buildSrc中配置相同Firebase依赖时,出现Kotlin版本不兼容错误,提示期望Kotlin 1.5.1模块,实际找到1.7.1版本。核心需求是通过自定义Gradle任务在同步时触发Firebase操作。
buildSrc配置
plugins { `kotlin-dsl` } repositories { google() mavenCentral() } dependencies { // firebase implementation(platform("com.google.firebase:firebase-bom:31.0.2")) implementation("com.google.firebase:firebase-firestore-ktx") }
错误信息
/Users/xx/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.7.10/0d0a9e3f3673ba/kotlin-stdlib-common-1.7.10.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.7.1, expected version is 1.5.1.
解决方案
方案1:指定kotlin-dsl插件版本匹配项目Kotlin版本
kotlin-dsl插件默认绑定的Kotlin版本可能低于项目使用的1.7.20,导致依赖冲突。需要在buildSrc的plugins块中指定与Kotlin 1.7.20兼容的kotlin-dsl版本(2.2.0版本对应Kotlin 1.7.20):
plugins { `kotlin-dsl` version "2.2.0" } repositories { google() mavenCentral() gradlePluginPortal() // 需添加此仓库以获取指定版本的kotlin-dsl插件 } dependencies { implementation(platform("com.google.firebase:firebase-bom:31.0.2")) implementation("com.google.firebase:firebase-firestore-ktx") }
方案2:添加依赖约束强制统一Kotlin版本
在buildSrc的dependencies中添加constraints,强制所有Kotlin相关依赖使用项目的1.7.20版本,覆盖Firebase依赖引入的旧版本:
plugins { `kotlin-dsl` } repositories { google() mavenCentral() } dependencies { constraints { implementation("org.jetbrains.kotlin:kotlin-stdlib:1.7.20") implementation("org.jetbrains.kotlin:kotlin-stdlib-common:1.7.20") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.20") } implementation(platform("com.google.firebase:firebase-bom:31.0.2")) implementation("com.google.firebase:firebase-firestore-ktx") }
补充说明
- 若使用方案1,需确保
gradlePluginPortal()仓库已添加,否则无法拉取指定版本的kotlin-dsl插件。 - 两种方案均可解决版本冲突,优先选择方案1,因为它从插件层面统一了Kotlin版本,避免后续潜在的依赖不一致问题。
内容的提问来源于stack exchange,提问作者virat
相关产品推荐
相关产品推荐

