Implementing Dagger2 with Kotlin
Most of you have heard about Kotlin which is now officially supported from Google itself. Thus I wont deep-dive into Kotlin, but you can follow this and this link as a starting point.
I am going to explain on how to implement Dagger 2 in your Android projects for using with Kotlin.
Firstly you have to configure Gradle build tool for supporting Kotlin
- Add Kotlin Gradle Plugin in your top build.gradle file:
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
- Add Kotlin plugins in your inner build.gradle file:
//Kotlin android extensions
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
//Kotlin Annotation Processing (KAPT) plugin
apply plugin: 'kotlin-kapt'
- Add dependency to your dependencies in inner build.gradle file:
implementation "com.google.dagger:dagger:$daggerVersion"
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
Creating Module
Suppose we want to create module named AppModule which takes our App class as a constructor parameter:
@Module
class AppModule(val app: App) {
@Provides
fun provideApp(): App = app
}
this will be equivalent to:
@Module
public class AppModule { private final App app; public AppModule(App app) {
this.app = app;
}
@Provides
Application provideApp() {
return app;
}
}
Creating component
We create AppComponent by injecting App class as below:
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
fun inject(app: App)
}
which is equivalent to:
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
void inject(App app);
}
if you want to include a dependency on your @Component you can do it same as module: dependencies = arrayOf(AnotherComponent::class)
and finally we implement it on our App:
class App : Application() {
val appComponent: AppComponent by lazy {
DaggerAppComponent
.builder()
.appModule(AppModule(this))
.build()
}
override fun onCreate() {
super.onCreate()
appComponent.inject(this)
}
fun appComponent() : AppComponent = appComponent
}
Creating custom scope
If you want to create a custom scope you can do it as following:
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class AppContextScope
notice that AnnotationRetention is a kotlin annotation(kotlin.annotation)
If you liked this article, be sure to click ❤ below and check my Play Store Apps