Android Kotlin:错误未解决参考:DaggerAppComponent

Android Kotlin : Error Unresolved reference: DaggerAppComponent

我今天已经将 Kotlin 插件安装到一个现有的 Dagger 2 项目中。在安装 Kotlin 之前,我对 Dagger 没有任何问题。然而,现在编译器抱怨:

Error:(5, 32) Unresolved reference: DaggerAppComponent
Error:Execution failed for task ':app:compileDebugKotlinAfterJava'.
> Compilation error. See log for more details
Error:(12, 21) Unresolved reference: DaggerAppComponent

项目gradle:

ext.kotlin_version = '1.1.1'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

模块gradle:

kapt {
    generateStubs = true
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'

    compile 'com.google.dagger:dagger:2.7'
    kapt 'com.google.dagger:dagger-compiler:2.7'

    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"


}

DaggerAppComponent 文件是自动生成的,所以我很困惑为什么会抛出一个未解决的引用错误。

我收到了相同的错误消息,但我的情况与您的不同。未解析的引用仅在生成签名的 APK 时出现。我是这样解决的:

app/build.gradle

kapt {
    generateStubs = true
}

dependencies {
    //...
    implementation 'com.google.dagger:dagger:2.9'
    kapt 'com.google.dagger:dagger-compiler:2.9'
}

我现在可以毫无错误地部署我签名的 APK

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'   

在你的依赖项中:

implementation "com.google.dagger:dagger:2.x"
implementation "com.google.dagger:dagger-android:2.x"
implementation "com.google.dagger:dagger-android-support:2.x"
kapt "com.google.dagger:dagger-compiler:2.x"
kapt "com.google.dagger:dagger-android-processor:2.x"

不要在 Kotlin 中使用 private 注入 dagger,在 Kotlin 中像这样使用它

@Inject
     internal lateinit

起初,重建后报错:

Unresolved reference: DaggerAppComponent

您应该尝试导入 (Alt + Enter) 该组件。

就我而言,截至

Kotlin version 1.5.30
Dagger version 2.35.1
Dagger support version 2.28.3

dagger 2(以上版本)和 kotlin 1.5.30 存在问题。当您尝试使用

运行 项目时
implementation 'com.google.dagger:dagger:2.35.1'
implementation 'com.google.dagger:dagger-android:2.35.1'
implementation 'com.google.dagger:dagger-android-support:2.28.3'
kapt 'com.google.dagger:dagger-compiler:2.28.3'
kapt 'com.google.dagger:dagger-android-processor:2.28.3'

它将失败并出现错误:

java.lang.reflect.InvocationTargetException

当我使用 Run with --stacktrace 时,我发现问题是:

IllegalStateException: Unsupported metadata version" in KaptWithoutKotlincTask with 1.5.0-M2

我发现这是因为 Dagger 使用旧版本的 kotlinx-metadata-jvm 库并且还不支持 kotlin 1.5 及更高版本。

因此,作为修复,我添加了:

kapt 'org.jetbrains.kotlinx:kotlinx-metadata-jvm:0.2.0'

我不知道是否有官方修复此问题,但这可能对某些人有所帮助。

N:B: 我尝试从 kapt 更改为 annotationProcessor,并认为项目已编译,但我仍然无法生成 DaggerAppComponent