ERROR : error.NonExistentClass Kotlin In multi module Dagger project
I'm using Dagger 2 and Kotlin for Android development. My project is also a multi-module project. My settings.gradle file is like this:
include :app
include :lib
I'm also maintaining the lib module.
In the Dagger Files (for example in the component), I try to get the item from other module. For example:
@Component
interface AppComponent{
fun getPresenter() : Presenter
}
The Presenter object is defined in lib module. I was working in linux environment and I'm using Android Studio 3 preview canary 5. The code is working well and I am able to generate APK.
But my company wanted to generate the APK using stable version of Android Studio. I'm using Android Studio 2.3.3.
When compiling the Android Project, I encountered this error:
error: error.NonExistentClass
The error appears when
:app:kaptDebugKotlin
is performed and caused by the dagger class cannot found, the class is defined in the other project. What can be the possible workaround for this? Sorry for my bad English.
Just add this to build gradle file to avoid the issues related NonExistentClass
kapt {
correctErrorTypes true
}
https://kotlinlang.org/docs/reference/kapt.html#non-existent-type-correction
The Root Cause
Basically, there's not much that can be done to fix this when using kapt
. To quote this link that tackles the same problem in another library that uses pre-processors (OrmaDatabase):
Because Kotlin makes its stubs before Java Annotation Processing runs, Kotlin knows just nothing about OrmaDatabase, and the name of the declaration in stubs will be error.NonExistentClass. This breaks the Annotation Processing tool. It's a kind of kapt limitation
How to fix it (the workaround)
Just use plain apt
or annotationProcessor
for running Dagger compiler. As soon as I changed:
kapt libs.daggerCompiler
to
annotationProcessor libs.daggerCompiler
in my module level build.gradle
file, I was able to get the errors. After you've fixed the errors, you gotta revert the line back to kapt
because otherwise dagger classes wouldn't be generated since they're defined in Kotlin.
I had a very similar situation with a NonExistentClass
error in a multi-module project using Dagger and turns out I forgot to add the kotlin library dependency. So, just adding it in the sub-module solved my problem:
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$rootProject.kotlinVersion"