Hilt basics
Why it matters
- Hilt is the standard DI framework in most mid-to-large Android codebases; interviewers expect you to read and extend a Hilt graph without guessing.
- Wrong scoping (everything
@Singleton, or an expensive client left unscoped) is a common Hilt bug in production: leaks, stale state, or several copies of something that should be shared. - Knowing
@Providesvs@Binds, qualifiers and assisted injection lets you extend an existing graph in a PR without breaking the build. - Hilt's errors arrive at build time as long Dagger messages; knowing the pieces is what lets you read them.
The simple explanation
- A restaurant kitchen has a recipe book (the Hilt graph). Each dish (class) lists its ingredients (constructor parameters), and the book is checked for missing ingredients before the restaurant opens (the build).
Hilt is a compile-time DI framework built on Dagger. An annotation processor (KSP in current projects, kapt in older ones) reads your annotations and generates the factories and components that build your objects. There is no reflection; a missing or duplicate binding fails the build.
Setup with KSP. Apply the com.google.devtools.ksp and com.google.dagger.hilt.android Gradle plugins, add implementation("com.google.dagger:hilt-android:<version>") and ksp("com.google.dagger:hilt-android-compiler:<version>"). Use the same version for both.
Declaring a dependency. Put @Inject on a class's constructor. Hilt now knows how to build it and passes its parameters from the graph. You never call that constructor yourself.
Modules teach Hilt about types it cannot build from an @Inject constructor: interfaces and third-party classes. A @Module must also carry @InstallIn(SomeComponent::class), which says which component (and so which lifetime) its bindings belong to.
@Providesis a function whose body builds the instance (Retrofit.Builder()...build()). It lives in anobjectmodule (or acompanion object).@Bindsis an abstract function that maps an interface to an implementation Hilt can already build. It lives in anabstract classorinterfacemodule.
Android entry points:
| Annotation | Goes on | Effect |
|---|---|---|
@HiltAndroidApp | Application subclass | Generates the root component; exactly one per app |
@AndroidEntryPoint | ComponentActivity, Fragment, View, Service, BroadcastReceiver | Injects @Inject fields when the system creates the class |
@HiltViewModel | ViewModel with an @Inject constructor | Obtained with hiltViewModel() in Compose or by viewModels() in an Activity / Fragment |
@ApplicationContext / @ActivityContext | Context parameter | Says which Context you get |
@AssistedInject + @Assisted | Constructor / parameter | Some values come from the caller, not the graph |
Qualifiers separate two bindings of the same type: @Named("baseUrl") String, or better, your own annotation marked @Qualifier (for example @IoDispatcher CoroutineDispatcher).
Scopes. A binding is unscoped by default: a new instance each time it is injected. A scope annotation that matches the component (@Singleton for SingletonComponent) makes it one instance per component. The next lesson covers the full hierarchy.
Outside entry points (a ContentProvider, a library callback), an @EntryPoint interface plus EntryPointAccessors.fromApplication(context, MyEntryPoint::class.java) pulls a dependency from the graph.
Notes
@HiltAndroidAppgoes on exactly oneApplicationsubclass, which must be registered in the manifest. If it is missing, opening an@AndroidEntryPointActivity crashes at runtime with an error asking for a Hilt Application.- Use
@Inject constructorfor classes you own. Field injection (@Inject lateinit var) is supported, but only for system-created classes marked@AndroidEntryPoint; the fields are set insuper.onCreate()(Activity) oronAttach()(Fragment). - A Fragment annotated
@AndroidEntryPointrequires its host Activity to be annotated too. @Providesgoes in anobject(or acompanion object);@Bindsis abstract and goes in anabstract classorinterface. An abstract module cannot also hold instance@Providesmethods.- Unscoped is the default: every injection gets a fresh instance. Add
@Singletonfor objects that are expensive or must be shared (OkHttpClient,Retrofit, a Room database), not by habit. @ApplicationContextgives the applicationContext; it has no Activity theme, so do not inflate views or show dialogs with it. Use@ActivityContextinsideActivityComponentor below.hiltViewModel()for Compose now lives inandroidx.hilt:hilt-lifecycle-viewmodel-compose(packageandroidx.hilt.lifecycle.viewmodel.compose); the older function inhilt-navigation-composestill works but is deprecated. In an Activity or Fragment useby viewModels().- A
@HiltViewModelcan receiveSavedStateHandlefrom Hilt directly. For values only the caller knows, use@HiltViewModel(assistedFactory = ...)with an@AssistedFactory. - Your own
@Qualifierannotations are safer than@Named("..."), because a typo in a string is just a different, missing binding. - Testing:
@HiltAndroidTestwithHiltAndroidRuleruns a generated test application;@TestInstallInreplaces a module for every test in the source set, and@UninstallModulesreplaces it for one test class.
Code example
A typical Hilt setup: a @Provides module for Retrofit, a @Binds module for a repository interface, a qualifier, a @HiltViewModel, and a screen that obtains it.
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.components.SingletonComponent
import javax.inject.Inject
import javax.inject.Qualifier
import javax.inject.Singleton
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
@Serializable
data class UserDto(val id: String, val name: String)
interface UserApi {
@GET("users/{id}")
suspend fun user(@Path("id") id: String): UserDto
}
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class BaseUrl
// Third-party objects Hilt cannot build from a constructor
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@BaseUrl
fun provideBaseUrl(): String = "https://api.example.com/"
@Provides
@Singleton // one Retrofit for the whole app
fun provideRetrofit(@BaseUrl baseUrl: String): Retrofit =
Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.build()
@Provides
@Singleton
fun provideUserApi(retrofit: Retrofit): UserApi = retrofit.create(UserApi::class.java)
}
interface UserRepository {
suspend fun userName(id: String): String
}
// Hilt can build this because of @Inject constructor
class UserRepositoryImpl @Inject constructor(
private val api: UserApi,
) : UserRepository {
override suspend fun userName(id: String): String = api.user(id).name
}
// Interface -> implementation
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
abstract fun bindUserRepository(impl: UserRepositoryImpl): UserRepository
}
@HiltViewModel
class UserViewModel @Inject constructor(
private val repository: UserRepository, // resolved through @Binds
) : ViewModel() {
private val _name = MutableStateFlow("")
val name: StateFlow<String> = _name.asStateFlow()
fun load(id: String) {
viewModelScope.launch {
_name.value = runCatching { repository.userName(id) }.getOrDefault("error")
}
}
}
@Composable
fun UserScreen(viewModel: UserViewModel = hiltViewModel()) {
val name by viewModel.name.collectAsStateWithLifecycle()
Text(name)
}RetrofitandUserApiuse@Providesbecause their instances come from a builder, not a constructor Hilt can call.UserRepositoryImplneeds no module of its own;@Bindsonly tells Hilt which class to use for the interface.@Singletonon the@Providesmethods makes oneRetrofitand oneUserApiper process. Installing a module inSingletonComponentdoes not scope anything by itself: without@Singleton, every injection would build a newRetrofit.- The
@BaseUrlqualifier keeps thisStringfrom clashing with any otherStringbinding in the graph. - The Activity hosting
UserScreenmust be annotated@AndroidEntryPoint, andhiltViewModel()comes fromandroidx.hilt:hilt-lifecycle-viewmodel-compose. In a Fragment you would writeprivate val viewModel: UserViewModel by viewModels().
Run the idea in plain Kotlin
Hilt generates factories like these at build time. Here they are written by hand: an unscoped factory builds a new object each call, and a scoped one caches the first instance.
interface Factory<T> { fun get(): T }
// What Hilt generates for an unscoped binding: build a new instance every time
class Unscoped<T>(private val create: () -> T) : Factory<T> {
override fun get(): T = create()
}
// What a scope annotation adds: build once per component, then reuse
class Scoped<T>(private val create: () -> T) : Factory<T> {
private var instance: T? = null
override fun get(): T = instance ?: create().also { instance = it }
}
var nextId = 1
class HttpClient { val id = nextId++ }
interface UserRepository { fun describe(): String }
class UserRepositoryImpl(private val client: HttpClient) : UserRepository {
val id = nextId++
override fun describe() = "repo#" + id + " using client#" + client.id
}
class UserViewModel(val repo: UserRepository)
// The "component": @Singleton HttpClient, unscoped repository bound to its interface
class AppComponent {
val client: Factory<HttpClient> = Scoped { HttpClient() }
val repository: Factory<UserRepository> = Unscoped { UserRepositoryImpl(client.get()) }
fun userViewModel() = UserViewModel(repository.get())
}
fun main() {
val component = AppComponent()
val first = component.userViewModel()
val second = component.userViewModel()
println("first: " + first.repo.describe())
println("second: " + second.repo.describe())
println("same repository? " + (first.repo === second.repo))
}Expected output:
first: repo#2 using client#1
second: repo#3 using client#1
same repository? false
In production
- After a refactor, network traces showed two different
OkHttpClientinstances in the app, each with its own connection pool and cache directory, and requests occasionally failed with a cache-lock warning in logcat. NetworkModulewas installed inSingletonComponent, but its@Provides fun provideOkHttp()had no@Singleton. The team assumed the component made it a singleton.- Every class that injected
OkHttpClient(Retrofit and an image loader) got a fresh client pointing at the same disk cache.
- They added a log line to
provideOkHttp()and saw it run twice on startup. - They annotated
provideOkHttp()andprovideRetrofit()with@Singleton; the log now runs once per process. - They added a
@HiltAndroidTestthat injectsOkHttpClientinto two fields and asserts both refer to the same instance.
- Users in dark mode reported a white flash and light-coloured views on the settings screen.
- A
@SingletonSettingsViewFactorytook an@ApplicationContextand used it to inflate views for the screen. - The application
Contextdoes not carry the Activity's theme, so the inflated views used the app's default theme instead of the Activity's.
- They reproduced it by enabling dark mode and opening the settings screen.
- They removed the
Contextfrom the singleton and made the screen inflate its views with its own ActivityContext(LayoutInflater.from(requireContext())in the Fragment). - Classes that genuinely need an Activity
Contextare now installed inActivityComponentand take@ActivityContext, so they cannot outlive the Activity.
Common mistakes
- Forgetting @InstallIn on a module. Hilt reports an error at build time because it does not know which component the module belongs to. Every
@Moduleneeds@InstallIn. - Thinking @InstallIn(SingletonComponent::class) makes a binding a singleton. It only decides where the binding lives. Without
@Singletonon the@Providesmethod or the class, a new instance is created every time. - Using @Provides when @Binds is enough.
fun provideRepo(impl: RepoImpl): Repo = implworks but needs a body and generates more code. Use@Bindsfor interface-to-implementation mappings; keep@Providesfor objects built in code. - Calling hiltViewModel() from a Fragment, or by hiltViewModel().
hiltViewModel()is a@Composablefunction. In an Activity or Fragment useby viewModels(); Hilt's default factory handles@HiltViewModelclasses. - Using @ApplicationContext for UI work. The application
Contexthas no Activity theme or window, so inflated views get the wrong theme and dialogs crash. Use the Activity'sContext. - A dependency cycle.
AneedsBandBneedsA; Dagger fails the build with "Found a dependency cycle". Redesign so one side does not need the other, or injectLazy<A>orProvider<A>to defer creation.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between @Provides and @Binds?”
“What happens when you inject an unscoped dependency?”
“How does Hilt integrate with Activities, Fragments and ViewModels?”
“How would you test code that uses Hilt?”
Quiz
Which annotation must appear on exactly one class in the app?
A @Provides function for OkHttpClient sits in a module installed in SingletonComponent but has no scope annotation. What happens?
How do you obtain a @HiltViewModel inside a Fragment annotated with @AndroidEntryPoint?
What does @Assisted do?
0 of 4 answered
Mini task
15-minute exercise: wire a repository into a ViewModel with Hilt
Setup: Use a project with Hilt applied, or add the com.google.devtools.ksp and com.google.dagger.hilt.android plugins plus hilt-android and ksp(hilt-android-compiler). Add @HiltAndroidApp to the Application class (registered in the manifest) and @AndroidEntryPoint to the main Activity. Add androidx.hilt:hilt-lifecycle-viewmodel-compose for hiltViewModel().
- Create an interface
UserRepositorywithsuspend fun fetchUser(): String. - Create
UserRepositoryImpl @Inject constructor()that returns a hardcoded string. - Create a
@Module @InstallIn(SingletonComponent::class) abstract class RepositoryModulethat@BindsUserRepositoryImpltoUserRepository. - Create a
@HiltViewModel class MainViewModel @Inject constructor(repo: UserRepository). Addfun loadUser()that launches inviewModelScope, callsfetchUser()and stores the result in aMutableStateFlow. - In a Composable, get the ViewModel with
hiltViewModel(), callloadUser()from aLaunchedEffect(Unit)and show the value withcollectAsStateWithLifecycle(). - Run the app and confirm the string appears.
- Add a qualifier
@Qualifier annotation class Greeting, a@Provides @Greeting fun greeting(): String = "Hello"in anobjectmodule, and inject@Greeting greeting: Stringinto the ViewModel. Prepend it to the user string.
Done condition: The app shows "Hello" plus the user string, no class calls a repository or ViewModel constructor itself, and removing the @Greeting annotation from the provider makes the build fail with a missing-binding error.