Constructor injection
A restaurant kitchen doesn’t make its own knives and pans; the restaurant supplies them. A cook just says “I need a pan” and gets one. With Hilt, a class says what it needs by listing it in its constructor and marking that constructor with @Inject. Hilt sees the whole list at compile time, figures out the order to create things in, and hands each class what it asked for.
Hilt is Dagger with a fixed set of Android components (SingletonComponent, ActivityRetainedComponent, ViewModelComponent, ActivityComponent, …) and generated entry points for framework classes. Constructor injection (@Inject constructor) is the default for your own types; Dagger generates factories and validates the full graph (missing bindings, cycles, scope mismatches) at build time, with no reflection at runtime. KSP processing is supported and much faster than kapt.
@HiltAndroidApp
class ShopApp : Application() // creates the app-wide container
@AndroidEntryPoint
class MainActivity : ComponentActivity() { // lets Hilt inject into this activity and its screens
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { ShopNavHost() }
}
}
class OrdersRepository @Inject constructor( // Hilt knows how to build it
private val api: ShopApi,
private val dao: OrderDao,
)
@HiltViewModel
class OrdersViewModel @Inject constructor(
private val repository: OrdersRepository,
savedStateHandle: SavedStateHandle, // provided by Hilt automatically
) : ViewModel() { /* … */ }
@Composable
fun OrdersScreen(viewModel: OrdersViewModel = hiltViewModel()) {
val orders by viewModel.orders.collectAsStateWithLifecycle()
OrdersList(orders)
}@HiltAndroidAppon theApplicationclass (registered in the manifest) starts Hilt.@AndroidEntryPointon each activity that uses injection.@Inject constructoron your own classes: no extra code needed to tell Hilt how to build them.@HiltViewModel+hiltViewModel()in Compose: Hilt creates the ViewModel with its dependencies, scoped to the screen’s back stack entry.- If something can’t be built (say,
ShopApiisn’t provided anywhere yet), the build fails with a message naming the missing type.
@HiltAndroidApp,@AndroidEntryPoint,@HiltViewModel+hiltViewModel(); constructor injection for own types.- Graph validated at compile time (missing bindings, cycles, scope errors); no runtime reflection. Use KSP.
SavedStateHandleis injectable into@HiltViewModels; assisted injection (@AssistedInject+@HiltViewModel(assistedFactory = …)) for runtime arguments.
Check this part
How does a class tell Hilt what it needs?
When do you find out a dependency can't be created?