Dependency injection with Hilt

Part 1 ( Introduction )

Noha Samir
2 min readJul 6, 2020

Content

What is dependency injection?

What is Hilt?

How to setup Hilt?

What is dependency injection?

Dependency means that one class use another class

Dependency injection means instead of each instance of Object1 constructing its own Object2 on initialization, it receives an Object2 as a parameter in its constructor

Car instance depend on Engine instance
A car depends on Engine
//Car depend on Engineclass Car(private val engine: Engine) {
init {
println("Car init")
}
fun start() = "Car started"
}
class Engine {
init {
println("Engine init")
}
}

What is Hilt?

Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project.

Hilt currently supports the following Android classes:

  • Application (by using @HiltAndroidApp)
  • Activity
  • Fragment
  • View
  • Service
  • BroadcastReceiver

How to setup Hilt?

1- Add the hilt-android-gradle-plugin plugin to your project's root build.gradle file :

buildscript {
...
dependencies {
...
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
}
}

2- Then, apply the Gradle plugin and add these dependencies in your app/build.gradle file:

...
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

android {
...
}

dependencies {
implementation "com.google.dagger:hilt-android:2.28-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
}

3- Create Application class that is annotated with @HiltAndroidApp

@HiltAndroidApp
class MyApplication : Application() { ... }

4- Add Application class to your AndroidManifest.xml

<application
android:name=".MyApplication"
...
>
</application>

Get the code

Get the code from GitHub: (Link)

$ git clone https://github.com/NohaSamir/HiltApplication/tree/2-HiltSetup

Up Next: Part 2 / Part 3

--

--