Using Dagger 2 with Kotlin
Dagger 2 is the best dependency injection framework in the Android community and is also open source. It is backed by Google and is widely used. Dependency injection is considered best practice and makes your code base scalable. In this recipe, we will learn how to use Dagger 2 for dependency injection in Kotlin.
Getting ready
We'll be using Android Studio 3.0 for coding purposes. First, we need to include Dagger 2 in the project, by adding the following lines to the build.gradle
file:
compile "com.google.dagger:dagger:$daggerVersion" kapt "com.google.dagger:dagger-compiler:$daggerVersion"
You need to replace $daggerVersion
with the latest version of Dagger2.
How to do it…
Before we move ahead, we need to understand how Dagger2 works. Dagger2 uses annotation to generate codes and uses it to access fields; therefore, it can't use private fields.
The following annotations are used in Dagger2:
@Module
and@Provides
: Define classes and methods that provide dependencies@Inject...