KAPT to KSP migration and Hilt

There is an issue with Dagger / Hilt when you migrate your project from the KAPT to KSP code generation plugin.

When you try to provide BuildConfig values through a Dagger module or if you try to provide DataBinding values, then we end up with the following error:

@Module
@InstallIn(SingletonComponent::class)
object KeypadModule {

    @Provides
    @ShuffledKeypad
    fun provideIsKeypadEnabled() = BuildConfig.IS_KEYPAD_ENABLED
}

Error:

e: [ksp] ModuleProcessingStep was unable to process 'com.test.keypad.KeypadModule' because 'error.NonExistentClass' could not be resolved.

Dependency trace:
    => element (OBJECT): com.test.keypad.KeypadModule
    => element (METHOD): provideIsKeypadEnabled()
    => type (ERROR return type): error.NonExistentClass

The fix is in the following Google ticket -> https://issuetracker.google.com/301245705

androidComponents {
onVariants(selector().all(), { variant ->
            afterEvaluate {
                // This is a workaround for https://issuetracker.google.com/301245705 which depends on internal
                // implementations of the android gradle plugin and the ksp gradle plugin which might change in the future
                // in an unpredictable way.
                project.tasks.getByName("ksp" + variant.name.capitalize() + "Kotlin") {
                    def buildConfigTask = (GenerateBuildConfig) project.tasks.getByName("generate${variant.name.capitalize()}BuildConfig")
                    ((AbstractKotlinCompileTool) it).setSource(buildConfigTask.sourceOutputDir)
                }
            }
        })
    }

You need to add the above code to your app build.gradle file.

Leave a comment