@HiltAndroidApp: The Entry Point for Hilt DI

@HiltAndroidApp is the main power switch for Hilt dependency injection. You place it on your Application class to trigger code generation and create the top-level dependency container.
WHY IT EXISTS Managing dependencies manually in a large Android app is complex and error-prone. Hilt automates this process, and @HiltAndroidApp is the designated starting point. It establishes a single, consistent entry point for Hilt to begin building the dependency graph for the entire application.
THE MENTAL MODEL Think of @HiltAndroidApp as the master switch for your app's entire electrical system (the dependency graph). You place this annotation on your main Application class, and it tells Hilt to power up, scan the project for all Hilt components, and prepare the main dependency container that will be available for the app's entire lifecycle.
HOW IT WORKS When you add @HiltAndroidApp to a class that extends Application, the Hilt annotation processor runs at compile time. It generates a new base class that your application class will inherit from. This generated code is responsible for creating the application-level dependency container, attaching it to the application's lifecycle, and making it available for injection into other Hilt components.
WHEN TO USE IT Use this annotation exactly once in your project, on your custom Application class. This is a mandatory first step for any app using Hilt. Every Hilt-enabled app must have a class annotated with @HiltAndroidApp.
WHEN NOT TO USE IT Do not use this on any class that is not your main Application subclass. You cannot have multiple classes with this annotation in a single app. Also, do not use it if you are using a different dependency injection framework like Dagger 2 manually or Koin.
ONE CANONICAL EXAMPLE First, create a custom Application class and annotate it: @HiltAndroidApp class MyApplication : Application() {}. Second, you must register this class in your AndroidManifest.xml file inside the <application> tag: android:name=".MyApplication". Forgetting this second step is a common error that causes a runtime crash, as the app won't know to use your Hilt-enabled application class.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.