Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [ Part 1]

Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [ Part 1]

Becoming Proficient in Dependency Injection with Hilt for Android (Kotlin)

ยท

1 min read

Table of contents

Getting Started with Hilt

  • Setting up Gradle

  • Application Class Configuration

To get started with Hilt in your Android project using Kotlin, follow these steps for setting up Gradle and configuring the Application class:

Setting up Gradle:

In our project's build.gradle file, make sure we have the necessary dependencies for Hilt:

buildscript {
     // ...
 dependencies {
        // ...
        classpath "com.google.dagger:hilt-android-gradle-plugin:2.40.5"
     }
}

allprojects {
     repositories {
        // ...
        mavenCentral()
     }
}

In our app's build.gradle file, apply the Hilt plugin and add the Hilt dependencies:

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

android {
     // ...
}

dependencies {
     // ...
     implementation "com.google.dagger:hilt-android:2.40.5"
     kapt "com.google.dagger:hilt-android-compiler:2.40.5"
}

Application Class Configuration:

In our Application class, add the @HiltAndroidApp annotation to enable Hilt for our application:

import android.app.Application
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class MyApplication : Application() {
     // Application code
}

With these setup steps, we have configured Hilt for your Android application. The @HiltAndroidApp annotation in the Application class tells Hilt to generate and manage the necessary components to enable dependency injection throughout our app.

Now you can start using Hilt annotations, such as @AndroidEntryPoint, to enable dependency injection in our activities, fragments, view models, and other Android components. Hilt will take care of creating and managing the necessary dependencies for us.

ย