Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 104 ยท Dependency Injection

Hilt

Learn Hilt on Android: @HiltAndroidApp, @AndroidEntryPoint, @HiltViewModel, modules with @Provides and @Binds, qualifiers, scopes, assisted injection and Koin.

In the previous lesson you wired an app by hand: constructors that receive their dependencies, and an AppContainer that builds and caches them. That works, but it grows. Every new class needs a line in the container, every screen needs a ViewModel factory, and scoped lifetimes need extra containers. Hilt is Google's recommended DI library for Android. You describe how to create objects with annotations, and Hilt generates the container code at compile time, including the ViewModel factories and the lifetimes tied to Android components.

Because the site has no Android toolchain, all Hilt code in this lesson is read-only. To make the ideas tangible, the TryIts build a tiny injector in plain Kotlin on Piston, using lambdas as recipes. It is a model, not Hilt: it resolves at runtime, while Hilt checks the whole graph at compile time and has no reflection cost. Each TryIt says what it stands in for.

What Hilt is built on

Hilt sits on top of Dagger, a compile-time DI framework. An annotation processor (KSP or kapt) reads your annotations, checks that every dependency can be satisfied, and generates plain Java/Kotlin code. If something is missing or two things are ambiguous, the build fails with a message that names the missing type. That is Hilt's biggest advantage over runtime containers: a wiring mistake never reaches a user.

Add it to Gradle (see Gradle for Android; check the releases for current versions):

Kotlin
// read-only: app/build.gradle.kts
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.android)
    alias(libs.plugins.ksp)
    alias(libs.plugins.hilt)               // com.google.dagger.hilt.android
}

dependencies {
    implementation(libs.hilt.android)
    ksp(libs.hilt.compiler)
    implementation(libs.androidx.hilt.navigation.compose)   // hiltViewModel() for Compose
}

The three entry annotations

1. @HiltAndroidApp on your Application class creates the app-level container and triggers the code generation. Remember to register the class in the manifest with android:name (see The Manifest and Resources).

Kotlin
// read-only
@HiltAndroidApp
class NotesApp : Application()

2. @AndroidEntryPoint on an Activity (or Fragment, Service, BroadcastReceiver) lets Hilt inject its fields. It is required on every Android class that either receives injected objects or hosts a Compose screen that calls hiltViewModel().

Kotlin
// read-only
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    @Inject lateinit var analytics: Analytics      // field injection: the only option for classes Android creates

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { NotesNavHost() }
    }
}

Field injection with @Inject lateinit var is the fallback for classes the system instantiates (activities have no constructor you control). Everywhere else, prefer constructor injection.

3. @Inject constructor tells Hilt how to build one of your own classes: it will look up each constructor parameter and pass it in.

Kotlin
// read-only
class NotesRepository @Inject constructor(
    private val api: NotesApi,
    private val dao: NotesDao,
) { /* ... */ }

For a ViewModel, add @HiltViewModel. Then in Compose, hiltViewModel() returns an instance scoped to the current navigation destination or activity, the same lifetimes you saw in ViewModel:

Kotlin
// read-only
@HiltViewModel
class NotesViewModel @Inject constructor(
    private val repository: NotesRepository,
    private val savedStateHandle: SavedStateHandle,     // provided by Hilt automatically
) : ViewModel() { /* ... */ }

@Composable
fun NotesRoute(viewModel: NotesViewModel = hiltViewModel()) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    NotesScreen(state, onAdd = viewModel::add)
}

Notice that there is no ViewModel factory anywhere. Hilt generated it.

Modules: classes you cannot annotate

You can put @Inject only on classes you own. Interfaces, third-party classes (Retrofit, Room, OkHttp) and objects built with builders need another way: a module. A module is an object or abstract class annotated with @Module and @InstallIn(...), which says in which component (and so with which lifetime) the bindings live.

@Provides is a function that builds an object, as a recipe:

Kotlin
// read-only
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Provides
    @Singleton
    fun provideOkHttp(): OkHttpClient =
        OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).build()

    @Provides
    @Singleton
    fun provideNotesApi(client: OkHttpClient): NotesApi =
        Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .client(client)                      // parameters are injected too
            .addConverterFactory(/* ... */)
            .build()
            .create(NotesApi::class.java)
}

@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {

    @Provides
    @Singleton
    fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
        Room.databaseBuilder(context, AppDatabase::class.java, "app.db").build()

    @Provides
    fun provideNotesDao(db: AppDatabase): NotesDao = db.notesDao()
}

@Binds is the lighter way to say "when someone asks for this interface, use that implementation". It is an abstract function with one parameter, and it generates no body:

Kotlin
// read-only
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {

    @Binds
    abstract fun bindNotesRepository(impl: DefaultNotesRepository): NotesRepository
}

Here DefaultNotesRepository needs @Inject constructor, and every class that asks for the NotesRepository interface receives it. In a test you replace this module with one that binds a fake (see Unit Testing ViewModels and Flows).

Components and scopes

Hilt gives each Android lifecycle its own container (a component), arranged in a hierarchy. A scope annotation says "create this once per component instance".

Component Lives as long as Scope annotation
SingletonComponent The app process @Singleton
ActivityRetainedComponent An activity, surviving rotation @ActivityRetainedScoped
ViewModelComponent One ViewModel @ViewModelScoped
ActivityComponent One activity instance @ActivityScoped
FragmentComponent / ViewComponent One fragment or view @FragmentScoped / @ViewScoped
ServiceComponent One service @ServiceScoped
flowchart TD
    S["SingletonComponent<br/>(app)"] --> AR["ActivityRetainedComponent"]
    AR --> VM["ViewModelComponent"]
    AR --> A["ActivityComponent"]
    A --> F["FragmentComponent"]
    F --> V["ViewComponent"]
    S --> SV["ServiceComponent"]

A child component can use everything its parents provide, but not the other way around.

Binding without a scope creates a new instance for each request. That is the default, and it is the right choice for cheap, stateless things. Add @Singleton to a class or a @Provides function when exactly one shared instance is needed, such as the database, the HTTP client or a repository with a cache. Choose the narrowest scope that works: a longer scope keeps objects alive longer, and every scoped object costs memory for its whole lifetime.

The first TryIt models these recipes: a registry of lambdas, singleton or not, with the same constructor-based wiring Hilt automates. Read it as a diagram of what generated code does.

Kotlin A mini injector made of lambdas (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the creation order in the log: asking for the ViewModel pulled the repository, which pulled the API client and analytics, and the singletons were created only once. Real Hilt does this at compile time and generates the same chain of constructor calls. Notice also how the two String bindings use qualifiers to stay apart, which brings us to the next topic.

Qualifiers

If you need two different objects of the same type (two Strings, two OkHttpClients, two CoroutineDispatchers), Hilt cannot tell them apart by type alone. A qualifier is a label attached to both the provider and the request. The built-in @Named("x") works, but a custom annotation is safer, because a typo in a string compiles fine and fails only when the app builds the graph:

Kotlin
// read-only
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class IoDispatcher

@Module
@InstallIn(SingletonComponent::class)
object DispatchersModule {
    @Provides @IoDispatcher
    fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
}

class NotesRepository @Inject constructor(
    private val dao: NotesDao,
    @IoDispatcher private val ioDispatcher: CoroutineDispatcher,   // easy to replace in tests
)

Injecting dispatchers like this is a standard Android testing pattern: a test supplies a test dispatcher, as shown in the testing lesson.

Assisted injection: runtime values plus dependencies

Sometimes a class needs both injected dependencies and a value that only exists at runtime, such as an item ID. Hilt cannot know the ID, so you mark it @Assisted and declare a factory; Hilt implements the factory, filling in the injected parameters while you provide the assisted ones.

Kotlin
// read-only
@HiltViewModel(assistedFactory = DetailViewModel.Factory::class)
class DetailViewModel @AssistedInject constructor(
    private val repository: NotesRepository,       // injected by Hilt
    @Assisted private val noteId: Long,            // provided by you
) : ViewModel() {

    @AssistedFactory
    interface Factory {
        fun create(noteId: Long): DetailViewModel
    }
}

@Composable
fun DetailRoute(noteId: Long) {
    val viewModel = hiltViewModel<DetailViewModel, DetailViewModel.Factory>(
        creationCallback = { factory -> factory.create(noteId) },
    )
    // ...
}

For navigation arguments you often do not need this at all: SavedStateHandle already contains them, as you saw in Passing Arguments and Results. Use assisted injection for values that do not come from the saved state.

The second TryIt models the idea: the registry provides a factory object that holds the injected repository and takes the runtime value. It also shows what a missing binding looks like in this runtime model (Hilt would stop the build instead) and detects a dependency cycle.

Kotlin Assisted factories, missing bindings and cycles (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the real tool, both errors surface as build errors, for example "[Dagger/MissingBinding] B cannot be provided without an @Inject constructor or a @Provides-annotated method". Read the whole message: Hilt prints the chain of classes that led to the problem.

Koin: a runtime alternative

Koin is a popular Kotlin-only DI library. You declare modules in a small DSL, almost exactly like the mini injector above, and Koin resolves them at runtime:

Kotlin
// read-only
val appModule = module {
    single { OkHttpClient() }
    single<NotesRepository> { DefaultNotesRepository(get(), get()) }
    viewModel { NotesViewModel(get()) }
}

class NotesApp : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin { androidContext(this@NotesApp); modules(appModule) }
    }
}

The trade-off is plain. Koin has no annotation processing, so builds are faster and the setup is simpler, but a missing binding fails when that code runs (you can add a checkModules test to catch it in CI). Hilt catches it at compile time and scales well on large, multi-module projects, at the cost of build time and a learning curve. Both are good choices, and the concepts in this track (constructor injection, scopes, composition root) apply to both. For a new project that follows Google's guidance, Hilt is the default; for a small app or a Kotlin Multiplatform project, Koin is common.

Common mistakes

  • Forgetting @AndroidEntryPoint on an Activity that hosts hiltViewModel(). The app crashes at runtime with a missing-component error.
  • Putting @Singleton on everything. Scope to the narrowest lifetime that is correct.
  • Using @Provides where @Binds is enough. @Binds is smaller and generates less code.
  • Mixing up @InstallIn components. A binding installed in ActivityComponent cannot be injected into a singleton.
  • Using @Named strings for important qualifiers; prefer custom annotations.
  • Injecting Context without a qualifier. Use @ApplicationContext (or @ActivityContext when you really need the activity) and never hold an activity in a singleton.
  • Field injection in your own classes. Use the constructor.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Hilt do that a hand-written AppContainer does not do for you?

    Hilt (through Dagger) reads annotations, generates the container and ViewModel factories, and fails the build if a dependency cannot be satisfied.
  2. 2. You need to inject an interface NotesRepository implemented by DefaultNotesRepository. Which is the most direct Hilt construct?

    @Binds maps an interface to an implementation that Hilt already knows how to build (through an @Inject constructor).
  3. 3. What is the default lifetime of a binding that has no scope annotation?

    Without a scope, Hilt creates a new instance for each injection point. Add @Singleton or another scope when you need sharing.
  4. 4. When would you use assisted injection?

    @Assisted marks the runtime parameters, and an @AssistedFactory creates the object. Hilt fills in the rest from the graph. Two bindings of one type call for a qualifier.
  5. 5. What is the main trade-off of Koin compared with Hilt?

    Koin is a runtime DSL with no code generation: simpler and faster to build, but graph mistakes appear at runtime unless you verify the modules in a test.

Summary

  • Hilt generates your DI container at compile time on top of Dagger, and fails the build when a dependency is missing or ambiguous.
  • Use @HiltAndroidApp on the Application, @AndroidEntryPoint on Android classes, @Inject constructor for your own classes and @HiltViewModel with hiltViewModel() for ViewModels.
  • Modules (@Module + @InstallIn) provide what you cannot annotate: @Provides builds an object, @Binds maps an interface to an implementation.
  • Scopes tie lifetimes to components (@Singleton, @ViewModelScoped, @ActivityScoped...); with no scope you get a new instance each time.
  • Qualifiers separate bindings of the same type; assisted injection mixes injected and runtime parameters.
  • Koin is a runtime DSL alternative: simpler and faster to build, but graph errors appear at runtime.
  • All Hilt and Koin code here is read-only; the TryIts are a lambda-based model of the same ideas.

Next: Unit Testing ViewModels and Flows