Get Dagger 2 Working in 3 Lines of Code — An Even Simpler Dagger 2 Tutorial

My previous Dagger 2 for dummies made Dagger 2 concepts simple. But it’s a relatively long article at 10 minutes of read time.

In programming, we find better methods and refactor code to simplify it further — I found a simpler way to explain Dagger 2. For those who feel a 10 minute read is too long, read this 4 minutes quick start tutorial.

Just 3 lines of code

To get Dagger 2 working, we’ll just need 3 lines of code!

class Info @Inject constructor()
@Component interface MagicBox { val info: Info }
fun main() { println(DaggerMagicBox.create().info) }

Just add this code in any Kotlin file in your Android Studio, and click the ▶️ button next to the fun main(), and it will execute.

Note: You’ll need to include the library first though in the build.gradle file

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

And

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// ... other dependencies ...
implementation 'com.google.dagger:dagger:2.13'
kapt

--

--