Dagger is a great tool for Dependency Injection. There are tons of great articles explaining why you should use Dependency Injection and how Dagger can help you achieve fruitful results.

However, I did not find any good introductory tutorials for newbies when I started learning it. So here I am. Showing you how to do Dependency Injection with Dagger in 4 simple steps in Android using Kotlin.

Step 1: In `app/build.gradle`, apply ‘kotlin-kapt’ and import the dagger libraries

Step 2: Create an object you would like to inject by using the keyword @Inject

Step 3: Declare where you are injecting to. In this case, it will be MainActivity.

Step 4: Inject the objects into your MainActivity

DaggerAppComponent will first show up in red as a compile error. Simply build the project and Dagger will generate it for you.

There you go! The simplest Dagger example you will ever find.

Just a little bit more info

You often only want a single copy of an object. To do that, simple add `@Singleton` in front of the class and the component. This will ensure only one copy of `Into` exist per `DaggerAppComponent` that’s built.

Next, create a `DaggerAppComponent` object at global level.

Now, you will see the same Info object being injected.

I intentionally made this tutorial super simple to help you take the first baby step. There are many more things you can do with Dagger. Good luck with the journey! You can find the source code on GitHub.

In the next tutorial, I will show you the Simplest Dagger Android Example that involves Android’s Application .

References

Dagger 2 for Dummies in Kotlin (with 20 lines of code)

World Shortest Dagger 2 Code?