Android library, Kotlin and Dagger2
I am creating an application that has two modules, a Core module, which is an Android library (com.android.library) and an application module (com.android.application).
After I converted the Java files to Kotlin, the project does not compile, giving me the error that the Dagger 2 generated files were not found (unresolved link). But those files that are currently being created in:
... core \ build \ generated \ source \ kapt \ release {my \ core \ names} \ DaggerBaseComponent.java
What am I missing?
build.gradle (main module)
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
...
android {
...
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
...
// Dagger.
kapt "com.google.dagger:dagger-compiler:2.10"
compile 'com.google.dagger:dagger:2.10'
provided 'javax.annotation:jsr250-api:1.0'
// Kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
build.gradle (app module)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
...
android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
...
// Dagger.
kapt "com.google.dagger:dagger-compiler:2.10"
compile 'com.google.dagger:dagger:2.10'
provided 'javax.annotation:jsr250-api:1.0'
// Kotlin
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
build.gradle (Project)
buildscript {
ext.kotlin_version = '1.1.2-3'
...
dependencies {
classpath 'com.android.tools.build:gradle:2.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
ApplicationContext.kt (of my main module)
class ApplicationContext : Application() {
var baseComponent: BaseComponent? = null
private set
override fun onCreate() {
super.onCreate()
initializeInjector()
}
private fun initializeInjector() {
// DaggerBaseComponent is and unresolved reference
baseComponent = DaggerBaseComponent.builder()
.appModule(AppModule(this))
.endpointModule(EndpointModule())
.build()
}
companion object {
operator fun get(context: Context): ApplicationContext {
return context.applicationContext as ApplicationContext
}
}
}
source to share
The problem was that Gradle couldn't find the files generated by the dagger kapt
, so I solved the problem by adding src/main/kapt
to my sourceSets config on my main module (lib):
build.gradle (main module)
android {
...
sourceSets {
main.java.srcDirs += ['src/main/kotlin', 'src/main/kapt']
}
}
After that, the Core module started to find its Dagger 2 generated files.
source to share