DEV Community

Cover image for What is dagger in Kotlin ?
DevByJESUS
DevByJESUS

Posted on

What is dagger in Kotlin ?

Hello everyone , currently i am learning kotlin and there is a bunch of annotation provided by a library called Dagger

So what is dagger ?
before dive into the core concepts we should know what is a dependency injection .

Dependency Injection

this is compose of two words Dependency, in OOP is a relation between object

image

and Injection the action of inject one object's resource inside the other object.

In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires.

So What is DAGGER ?

dagger is a library that facilitate dependency injection in kotlin . it is based on annotations

@Module and @Provides: define classes and methods which provide dependencies.

@Inject : request dependencies. Can be used on a constructor, a field, or a method.

@Component : enable selected modules and used for performing dependency injection

example below , and step

  1. 1) you should create a kotlin class and add the annotation @HiltAndroidApp to use Dagger in your android app
import android.app.Application
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class AllApplication: Application() {
}

Enter fullscreen mode Exit fullscreen mode
  1. 2) Secondly you have to modify you AndroidManifest.xml file to add the class we have currently created , in the Application tag like below
 <application
        android:name=".AllApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
...
Enter fullscreen mode Exit fullscreen mode

After all these steps you are ready to go with the differents annotations

There is only Dagger ?

No there is another library which name is Koin
next time i will do a comparison between those two libraries.

Documentation of Dagger

explanation video

Top comments (0)