Android kotlin-gradle-plugin升级到1.7.10引发的编译问题

班展
2023-12-01

前言

kotlin-gradle-plugin1.6.21升级到1.7.10引发了一系列报错。

buildscript {
    ext.kotlin_version = '1.7.10'
    ext.hilt_version = '2.41'
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
dependencies {
    //room
    def room_version = "2.4.2"
    implementation "androidx.room:room-ktx:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
     //hilt,每个module都需要添加
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
}

Room

项目room库的版本为2.4.2,出现了如下两个问题:

There are multiple good constructors and Room will pick the no-arg constructor.
 You can use the @Ignore annotation to eliminate unwanted constructors.

报错中已经说明了解决方案:

实体有多个构造函数的时候可以使用 @Ignore注解忽略掉其余的构造函数只保留一个 。

经过测试发现kotlin-gradle-plugin最新的1.7.0版本,build下会生成kapt3/stubs目录会将所有的kotlin代码编译成java代码。
如果kotlin类的构造函数 添加了@JvmOverloads注解,便会生成多个构造函数。

另一个问题:

Not sure how to convert a Cursor to this method's return type (java.lang.Object).
    public abstract java.lang.Object getUsers(@org.jetbrains.annotations.NotNull()

解决方案:

  1. room 升级到2.5.0-alpha02
If you using kotlin version (1.7.0) should work with room latest alpha version (2.5.0-alpha02)
  1. kotlin 版本降级到1.6.20
If you want using room in stable version (2.4.2) should work with kotlin version (1.6.20)

Hilt

Hilt的版本是2.41,出现了

����: [Hilt]
 Unsupported metadata version. Check that your Kotlin version is >= 1.0:   
 java.lang.IllegalStateException: Unsupported metadata version. Check that your Kotlin version is >= 1.0

升级hitl到2.43.2版本解决:
ext.hilt_version = '2.43.2'

参考

https://blog.csdn.net/weixin_41104307/article/details/125492071

 类似资料: