How it works
Dependency injection (DI) means a class declares what it needs, typically in its constructor, and something else supplies it. Dagger does this with generated code: annotations such as @Inject and @Module describe how to build each object, and a code generator writes the wiring at build time, so a missing dependency is a compile error rather than a crash. Hilt, from Google, sits on top of Dagger and removes most of its setup on Android.
With Hilt you annotate the Application class with @HiltAndroidApp, screens with @AndroidEntryPoint and ViewModels with @HiltViewModel; modules marked @InstallIn tie each object to a lifetime, such as the whole app or a single screen. Tests can swap in a fake repository. Dagger and Hilt support KSP, which builds faster than the older kapt. Hilt is Android-only, so Kotlin Multiplatform projects often use lighter options such as Koin.
Hilt and Dagger pros and cons
Pros
- Mistakes in the wiring show up at compile time, not in users' hands
- Standard Android integration for activities, ViewModels and WorkManager
- Makes swapping in fakes for tests straightforward
- Generated code is fast at runtime, with no reflection
Cons
- Annotations and generated code add build time
- Error messages can be long and hard to read
- A lot of concepts for a small app
- Android-only; shared Kotlin Multiplatform code needs another approach
When to use Hilt and Dagger
Pick it when
- Medium to large Android apps with many screens and shared services
- Teams that write unit tests and want easy fakes
Skip it when
- A small app, where passing objects by hand is simpler
- Shared Kotlin Multiplatform code, where Koin or manual wiring fits better
Hilt and Dagger pricing
Related terms
More in Mobile apps
Android building blocks