Hilt basics

Learn Hilt dependency injection for Android: how the graph is checked at compile time, and how to inject ViewModels, qualifiers and assisted values. About 25 minutes.

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 @Provides vs @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.

  • @Provides is a function whose body builds the instance (Retrofit.Builder()...build()). It lives in an object module (or a companion object).
  • @Binds is an abstract function that maps an interface to an implementation Hilt can already build. It lives in an abstract class or interface module.

Android entry points:

AnnotationGoes onEffect
@HiltAndroidAppApplication subclassGenerates the root component; exactly one per app
@AndroidEntryPointComponentActivity, Fragment, View, Service, BroadcastReceiverInjects @Inject fields when the system creates the class
@HiltViewModelViewModel with an @Inject constructorObtained with hiltViewModel() in Compose or by viewModels() in an Activity / Fragment
@ApplicationContext / @ActivityContextContext parameterSays which Context you get
@AssistedInject + @AssistedConstructor / parameterSome 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

  • @HiltAndroidApp goes on exactly one Application subclass, which must be registered in the manifest. If it is missing, opening an @AndroidEntryPoint Activity crashes at runtime with an error asking for a Hilt Application.
  • Use @Inject constructor for classes you own. Field injection (@Inject lateinit var) is supported, but only for system-created classes marked @AndroidEntryPoint; the fields are set in super.onCreate() (Activity) or onAttach() (Fragment).
  • A Fragment annotated @AndroidEntryPoint requires its host Activity to be annotated too.
  • @Provides goes in an object (or a companion object); @Binds is abstract and goes in an abstract class or interface. An abstract module cannot also hold instance @Provides methods.
  • Unscoped is the default: every injection gets a fresh instance. Add @Singleton for objects that are expensive or must be shared (OkHttpClient, Retrofit, a Room database), not by habit.
  • @ApplicationContext gives the application Context; it has no Activity theme, so do not inflate views or show dialogs with it. Use @ActivityContext inside ActivityComponent or below.
  • hiltViewModel() for Compose now lives in androidx.hilt:hilt-lifecycle-viewmodel-compose (package androidx.hilt.lifecycle.viewmodel.compose); the older function in hilt-navigation-compose still works but is deprecated. In an Activity or Fragment use by viewModels().
  • A @HiltViewModel can receive SavedStateHandle from Hilt directly. For values only the caller knows, use @HiltViewModel(assistedFactory = ...) with an @AssistedFactory.
  • Your own @Qualifier annotations are safer than @Named("..."), because a typo in a string is just a different, missing binding.
  • Testing: @HiltAndroidTest with HiltAndroidRule runs a generated test application; @TestInstallIn replaces a module for every test in the source set, and @UninstallModules replaces 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)
}
  • Retrofit and UserApi use @Provides because their instances come from a builder, not a constructor Hilt can call. UserRepositoryImpl needs no module of its own; @Binds only tells Hilt which class to use for the interface.
  • @Singleton on the @Provides methods makes one Retrofit and one UserApi per process. Installing a module in SingletonComponent does not scope anything by itself: without @Singleton, every injection would build a new Retrofit.
  • The @BaseUrl qualifier keeps this String from clashing with any other String binding in the graph.
  • The Activity hosting UserScreen must be annotated @AndroidEntryPoint, and hiltViewModel() comes from androidx.hilt:hilt-lifecycle-viewmodel-compose. In a Fragment you would write private 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

Two Retrofit clients and a doubled connection pool
  • After a refactor, network traces showed two different OkHttpClient instances in the app, each with its own connection pool and cache directory, and requests occasionally failed with a cache-lock warning in logcat.
  • NetworkModule was installed in SingletonComponent, 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.
The fix
  • They added a log line to provideOkHttp() and saw it run twice on startup.
  • They annotated provideOkHttp() and provideRetrofit() with @Singleton; the log now runs once per process.
  • They added a @HiltAndroidTest that injects OkHttpClient into two fields and asserts both refer to the same instance.
Wrong theme because of @ApplicationContext
  • Users in dark mode reported a white flash and light-coloured views on the settings screen.
  • A @Singleton SettingsViewFactory took an @ApplicationContext and used it to inflate views for the screen.
  • The application Context does not carry the Activity's theme, so the inflated views used the app's default theme instead of the Activity's.
The fix
  • They reproduced it by enabling dark mode and opening the settings screen.
  • They removed the Context from the singleton and made the screen inflate its views with its own Activity Context (LayoutInflater.from(requireContext()) in the Fragment).
  • Classes that genuinely need an Activity Context are now installed in ActivityComponent and 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 @Module needs @InstallIn.
  • Thinking @InstallIn(SingletonComponent::class) makes a binding a singleton. It only decides where the binding lives. Without @Singleton on the @Provides method or the class, a new instance is created every time.
  • Using @Provides when @Binds is enough. fun provideRepo(impl: RepoImpl): Repo = impl works but needs a body and generates more code. Use @Binds for interface-to-implementation mappings; keep @Provides for objects built in code.
  • Calling hiltViewModel() from a Fragment, or by hiltViewModel(). hiltViewModel() is a @Composable function. In an Activity or Fragment use by viewModels(); Hilt's default factory handles @HiltViewModel classes.
  • Using @ApplicationContext for UI work. The application Context has no Activity theme or window, so inflated views get the wrong theme and dialogs crash. Use the Activity's Context.
  • A dependency cycle. A needs B and B needs A; Dagger fails the build with "Found a dependency cycle". Redesign so one side does not need the other, or inject Lazy<A> or Provider<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().

  1. Create an interface UserRepository with suspend fun fetchUser(): String.
  2. Create UserRepositoryImpl @Inject constructor() that returns a hardcoded string.
  3. Create a @Module @InstallIn(SingletonComponent::class) abstract class RepositoryModule that @Binds UserRepositoryImpl to UserRepository.
  4. Create a @HiltViewModel class MainViewModel @Inject constructor(repo: UserRepository). Add fun loadUser() that launches in viewModelScope, calls fetchUser() and stores the result in a MutableStateFlow.
  5. In a Composable, get the ViewModel with hiltViewModel(), call loadUser() from a LaunchedEffect(Unit) and show the value with collectAsStateWithLifecycle().
  6. Run the app and confirm the string appears.
  7. Add a qualifier @Qualifier annotation class Greeting, a @Provides @Greeting fun greeting(): String = "Hello" in an object module, and inject @Greeting greeting: String into 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.

Next: Hilt scopes and components