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

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

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

ยท

2 min read

Understanding Hilt Annotations

  • @HiltAndroidApp

  • @AndroidEntryPoint

  • @HiltAndroidApp

The @HiltAndroidApp annotation is used to mark the Application class as the entry point for Hilt in an Android application. This annotation enables Hilt to generate and manage the necessary components to enable dependency injection throughout the app.

Example:

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

In this example, the MyApplication class is marked with @HiltAndroidApp, indicating that it serves as the entry point for Hilt. By applying this annotation, Hilt generates a MyApplication_HiltComponents class, which contains the necessary Dagger/Hilt components for the dependency injection.

@AndroidEntryPoint:

The @AndroidEntryPoint annotation is used to mark Android components (Activities, Fragments, ViewModels, etc.) as entry points for Hilt's dependency injection. This annotation allows Hilt to inject the required dependencies into these components automatically.

Example - Using @AndroidEntryPoint with an Activity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    // Injected dependencies can be used here
    // ...

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // ...
    }
}

In this example, the MainActivity class is marked with @AndroidEntryPoint. This annotation tells Hilt to generate code to inject the required dependencies into the MainActivity when it's created. Any dependencies that MainActivity needs, such as ViewModel, can be annotated with @Inject, and Hilt will automatically provide those dependencies.

Using @AndroidEntryPoint is essential to enable Hilt's automatic dependency injection in Android components, making the code cleaner and more maintainable by eliminating the need for manual dependency management.

ย