添加Room依赖后遭遇Kotlin版本不兼容错误,调整版本仍无法解决的技术咨询
Hey there! Let's tackle this incompatible Kotlin version error you're hitting with Room. The core issue is straightforward: your project uses Kotlin 1.5.31, but Room 2.4.3 was compiled with Kotlin 1.7.1—their metadata versions don't play nice together. Here are two solid solutions to fix this:
Option 1: Upgrade Kotlin (and Compose) to Match Room 2.4.3
Room 2.4.x requires Kotlin 1.6 or higher, and since Room 2.4.3 is built with Kotlin 1.7.1, we'll upgrade your project's Kotlin version to a compatible release. Also, your Compose version (1.1.0-beta01) is tied to Kotlin 1.5.31, so we need to upgrade Compose too to avoid further mismatches.
Update your project-level
build.gradlefile:buildscript { ext { compose_version = '1.3.0' // Compose 1.3.0 works with Kotlin 1.7.20 } dependencies { classpath("com.google.dagger:hilt-android-gradle-plugin:2.42") } } // 顶级构建文件,可添加适用于所有子项目/模块的配置选项。 plugins { id 'com.android.application' version '7.2.1' apply false id 'com.android.library' version '7.2.1' apply false id 'org.jetbrains.kotlin.android' version '1.7.20' apply false // Upgrade Kotlin version } task clean(type: Delete) { delete rootProject.buildDir }Sync your Gradle project, then go to File > Invalidate Caches / Restart to clear any stale build artifacts.
Option 2: Downgrade Room to Match Your Current Kotlin Version
If you don't want to upgrade Kotlin and Compose right now, you can downgrade Room to a version compatible with Kotlin 1.5.x. Room 2.3.x is built for Kotlin 1.5, so this will work seamlessly with your existing setup.
Update your app-level build.gradle file:
dependencies{ def room_version = "2.3.0" // Downgrade to Room 2.3.0 //room依赖 implementation("androidx.room:room-runtime:$room_version") annotationProcessor("androidx.room:room-compiler:$room_version") // 使用Kotlin注解处理工具(kapt) kapt("androidx.room:room-compiler:$room_version") implementation("androidx.room:room-ktx:$room_version") }
Again, sync Gradle and invalidate caches to ensure all changes take effect.
Quick Check
Make sure your app-level build.gradle has the kotlin-kapt plugin enabled (it should be in the top plugins block) since you're using kapt for Room's annotation processing:
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'kotlin-kapt' // Ensure this line exists // Other plugins like Hilt if needed }
Either solution should resolve the "incompatible version of Kotlin" error. Pick the one that fits your project's needs best!
内容的提问来源于stack exchange,提问作者Sky

