New

🧩 Hilt Tutorial: Dependency Injection in Jetpack Compose

Build a Study Tasks app where Hilt creates the repository, the settings store and the ViewModel for you, then swap in a fake for tests.

Beginner ⏱️ ~40 minutes 🧰 Kotlin, Jetpack Compose, Hilt 2.60.1, KSP
← Android Track

What You'll Build in This Hilt Tutorial

This Hilt tutorial adds dependency injection to a small Study Tasks app built with Jetpack Compose. You will write a repository, a settings store and a ViewModel, and let Hilt create and connect all of them. By the end you will know the six annotations that cover most real apps and how to replace a real class with a fake in a test.

Dependency injection means a class receives the objects it needs instead of creating them itself. Without it, a ViewModel might call TaskRepository() directly, which makes it hard to share one repository between screens or to test the ViewModel with fake data. Hilt, Google's recommended dependency injection library for Android, is built on Dagger and generates the wiring code at compile time. If you read the short dependency injection topic in our Android track, this lesson is the full, hands-on version.

Prerequisites

  • Kotlin, Compose state and ViewModels. Our Compose state management guide and the Notes app project cover these.
  • A recent Android Studio and a new Empty Activity (Compose) project.
  • Android Gradle Plugin 9.2 or newer: the Hilt Gradle plugin 2.59+ needs AGP 9, and androidx.hilt 1.4.0 needs AGP 9.2 for Compose.
  • minSdk 23 or higher (required since Hilt 2.60) and Java 17.

Add Hilt Dependency Injection Step by Step

1 Add the Hilt and KSP Gradle setup

Add these entries to gradle/libs.versions.toml. The versions are the latest stable releases on November 30, 2026: Dagger/Hilt 2.60.1, KSP 2.3.14 and androidx.hilt 1.4.0. KSP versions no longer have to match your Kotlin version.

[versions]
hilt = "2.60.1"
ksp = "2.3.14"
androidxHilt = "1.4.0"

[libraries]
hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt" }
hilt-compiler = { module = "com.google.dagger:hilt-compiler", version.ref = "hilt" }
hilt-android-testing = { module = "com.google.dagger:hilt-android-testing", version.ref = "hilt" }
androidx-hilt-viewmodel-compose = { module = "androidx.hilt:hilt-lifecycle-viewmodel-compose", version.ref = "androidxHilt" }

[plugins]
hilt-android = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }

Declare both plugins in the root build.gradle.kts, then apply them and add the libraries in app/build.gradle.kts, and sync:

// build.gradle.kts (project root)
plugins {
    // ...existing plugins
    alias(libs.plugins.hilt.android) apply false
    alias(libs.plugins.ksp) apply false
}

// app/build.gradle.kts
plugins {
    // ...existing plugins
    alias(libs.plugins.ksp)
    alias(libs.plugins.hilt.android)
}

dependencies {
    // ...existing dependencies
    implementation(libs.hilt.android)
    ksp(libs.hilt.compiler)
    implementation(libs.androidx.hilt.viewmodel.compose)
}

Google's own Hilt guide still shows an older version in one snippet. Use hilt-compiler with the same version as hilt-android, as the Dagger setup page does.

2 Create the Application class with @HiltAndroidApp

Every Hilt app needs an Application class annotated with @HiltAndroidApp. It is where Hilt creates the app-wide container that lives as long as the app.

import android.app.Application
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class StudyApp : Application()

Register it in AndroidManifest.xml. Forgetting this line is the most common Hilt crash for beginners:

<application
    android:name=".StudyApp"
    ... >

3 Write classes Hilt can build with @Inject

Adding @Inject to a constructor tells Hilt "you may create this class, and here is what it needs". The repository is defined as an interface so the app and the tests can use different implementations. @Singleton makes Hilt share one instance across the whole app.

import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

data class Task(val id: Int, val title: String, val done: Boolean = false)

interface TaskRepository {
    val tasks: StateFlow<List<Task>>
    fun add(title: String)
    fun toggle(id: Int)
}

@Singleton
class InMemoryTaskRepository @Inject constructor() : TaskRepository {
    private val _tasks = MutableStateFlow(
        listOf(Task(1, "Revise Kotlin basics"), Task(2, "Read the Hilt guide"))
    )
    override val tasks: StateFlow<List<Task>> = _tasks.asStateFlow()
    private var nextId = 3

    override fun add(title: String) {
        _tasks.update { it + Task(nextId++, title) }
    }

    override fun toggle(id: Int) {
        _tasks.update { list ->
            list.map { if (it.id == id) it.copy(done = !it.done) else it }
        }
    }
}

4 Teach Hilt with a module: @Binds and @Provides

Hilt cannot guess two things on its own: which class to use for an interface, and how to build types you did not write, such as SharedPreferences. You answer both in a module: a class marked @Module and @InstallIn, which says which container the bindings belong to.

import android.content.Context
import android.content.SharedPreferences
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Inject
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
    // "When someone asks for TaskRepository, give them InMemoryTaskRepository"
    @Binds
    abstract fun bindTaskRepository(impl: InMemoryTaskRepository): TaskRepository
}

@Module
@InstallIn(SingletonComponent::class)
object StorageModule {
    // A function with a body, for a type we cannot add @Inject to
    @Provides
    @Singleton
    fun provideSharedPreferences(
        @ApplicationContext context: Context
    ): SharedPreferences =
        context.getSharedPreferences("study_prefs", Context.MODE_PRIVATE)
}

class SettingsStore @Inject constructor(
    private val prefs: SharedPreferences
) {
    fun userName(): String = prefs.getString(KEY_NAME, "Learner") ?: "Learner"
    fun saveUserName(name: String) = prefs.edit().putString(KEY_NAME, name).apply()

    private companion object { const val KEY_NAME = "user_name" }
}

@ApplicationContext is a built-in qualifier, so you never pass a Context around by hand. SettingsStore needs no module at all: its constructor has @Inject and Hilt already knows how to make a SharedPreferences.

5 Inject into a ViewModel with @HiltViewModel

Mark the ViewModel with @HiltViewModel and give it an @Inject constructor. Hilt passes in the repository and the settings store.

import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.StateFlow

@HiltViewModel
class TaskViewModel @Inject constructor(
    private val repository: TaskRepository,
    settings: SettingsStore
) : ViewModel() {
    val userName: String = settings.userName()
    val tasks: StateFlow<List<Task>> = repository.tasks

    fun add(title: String) {
        if (title.isNotBlank()) repository.add(title.trim())
    }

    fun toggle(id: Int) = repository.toggle(id)
}

6 Use hiltViewModel() in Compose with @AndroidEntryPoint

Annotate the activity with @AndroidEntryPoint so Hilt can serve it, then get the ViewModel in a composable with hiltViewModel(). Note the import: since androidx.hilt 1.3.0 the function lives in androidx.hilt.lifecycle.viewmodel.compose. The older androidx.hilt.navigation.compose version is deprecated.

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { MaterialTheme { TaskScreen() } }
    }
}

@Composable
fun TaskScreen(viewModel: TaskViewModel = hiltViewModel()) {
    val tasks by viewModel.tasks.collectAsState()
    var newTitle by rememberSaveable { mutableStateOf("") }

    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text(
            "Hi ${viewModel.userName}, ${tasks.count { !it.done }} tasks left",
            style = MaterialTheme.typography.titleLarge
        )
        Row(verticalAlignment = Alignment.CenterVertically) {
            OutlinedTextField(
                value = newTitle,
                onValueChange = { newTitle = it },
                label = { Text("New task") },
                modifier = Modifier.weight(1f)
            )
            Spacer(Modifier.width(8.dp))
            Button(onClick = { viewModel.add(newTitle); newTitle = "" }) { Text("Add") }
        }
        LazyColumn {
            items(tasks, key = { it.id }) { task ->
                Row(
                    Modifier.fillMaxWidth()
                        .clickable { viewModel.toggle(task.id) }
                        .padding(vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Checkbox(checked = task.done, onCheckedChange = { viewModel.toggle(task.id) })
                    Text(task.title)
                }
            }
        }
    }
}

Run the app. Notice that nothing in this file creates a repository or a SharedPreferences: Hilt built the whole chain TaskViewModel → TaskRepository + SettingsStore → SharedPreferences → Context. Rotate the screen and the tasks stay, because the ViewModel and the singleton repository survive configuration changes.

7 Choose the right scope

Every binding belongs to a container (Hilt calls it a component), and a scope annotation decides how long one instance is shared. Unscoped bindings get a new instance each time they are requested, which is the right default for cheap classes.

ComponentScope annotationOne instance lives
SingletonComponent@SingletonFor the whole app
ActivityRetainedComponent@ActivityRetainedScopedAcross an activity's configuration changes
ViewModelComponent@ViewModelScopedAs long as one ViewModel
ActivityComponent@ActivityScopedFrom an activity's onCreate to onDestroy
ServiceComponent@ServiceScopedAs long as one service

Use @Singleton for things that hold shared state or are expensive to build, such as a repository, a database or a Retrofit client. Our Weather app project is a good place to practise: move its Retrofit setup into a @Provides function.

8 Swap in a fake for tests with @TestInstallIn

This is where dependency injection pays off. Add the testing library, a custom test runner that starts HiltTestApplication, and a test module that replaces RepositoryModule for every instrumented test:

// app/build.gradle.kts
android {
    defaultConfig {
        testInstrumentationRunner = "com.example.studytasks.HiltTestRunner"
    }
}
dependencies {
    androidTestImplementation(libs.hilt.android.testing)
    kspAndroidTest(libs.hilt.compiler)
}

// src/androidTest/.../HiltTestRunner.kt
// imports: android.app.Application, android.content.Context,
// androidx.test.runner.AndroidJUnitRunner, dagger.hilt.android.testing.HiltTestApplication
class HiltTestRunner : AndroidJUnitRunner() {
    override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application =
        super.newApplication(cl, HiltTestApplication::class.java.name, context)
}

// src/androidTest/.../FakeRepositoryModule.kt
// imports: dagger.Binds, dagger.Module, dagger.hilt.components.SingletonComponent,
// dagger.hilt.testing.TestInstallIn, javax.inject.*, kotlinx.coroutines.flow.*
@Singleton
class FakeTaskRepository @Inject constructor() : TaskRepository {
    private val _tasks = MutableStateFlow(listOf(Task(99, "Fake task")))
    override val tasks: StateFlow<List<Task>> = _tasks
    override fun add(title: String) { _tasks.update { it + Task(it.size + 100, title) } }
    override fun toggle(id: Int) {}
}

@Module
@TestInstallIn(components = [SingletonComponent::class], replaces = [RepositoryModule::class])
abstract class FakeRepositoryModule {
    @Binds
    abstract fun bindFake(fake: FakeTaskRepository): TaskRepository
}

// src/androidTest/.../TaskRepositoryTest.kt
// imports: dagger.hilt.android.testing.HiltAndroidRule, dagger.hilt.android.testing.HiltAndroidTest,
// javax.inject.Inject, org.junit.Assert.assertEquals, org.junit.Before, org.junit.Rule, org.junit.Test
@HiltAndroidTest
class TaskRepositoryTest {
    @get:Rule
    val hiltRule = HiltAndroidRule(this)

    @Inject
    lateinit var repository: TaskRepository

    @Before
    fun setUp() = hiltRule.inject()

    @Test
    fun usesTheFakeRepository() {
        assertEquals("Fake task", repository.tasks.value.first().title)
    }
}

Change com.example.studytasks to your package name. Google recommends @TestInstallIn over @UninstallModules when the same fake is used in many tests, because it avoids building a new set of components for each test class.

9 Fix the three most common Hilt errors

  • "Hilt Activity must be attached to an @HiltAndroidApp Application": the android:name=".StudyApp" line is missing from the manifest, or the class lacks @HiltAndroidApp.
  • "[Dagger/MissingBinding] … cannot be provided without an @Inject constructor or an @Provides-annotated method": Hilt does not know how to build a type. Add @Inject constructor to the class, a @Binds for an interface, or a @Provides function.
  • Gradle sync or plugin errors after adding Hilt: check that AGP is 9.2 or newer, minSdk is at least 23, and the KSP plugin is applied in the app module. If Gradle fails with a long "assembleDebug" error, our Gradle assembleDebug fix guide explains how to read it.

Practice Task

Extend the Study Tasks app on your own, then check yourself with the quiz below.

  1. Add a text field and button that call SettingsStore.saveUserName() through the ViewModel, and show the new name after restarting the app.
  2. Replace InMemoryTaskRepository with a Room-backed repository, following the Notes app project. Provide the database and DAO from a @Provides @Singleton module. Only RepositoryModule should need to change.
  3. Create a @ViewModelScoped class (for example, a draft holder) and inject it into TaskViewModel.
  4. Write a second test that calls repository.add("Revise scopes") on the fake and checks the list size.

Hilt Tutorial Quiz

Five quick questions on this tutorial.

Frequently Asked Questions

What is Hilt in Android?

Hilt is Google's dependency injection library for Android, built on top of Dagger. It generates the code that creates your objects and passes them to activities, ViewModels and other classes, so you do not wire them up by hand.

Should I use KSP or kapt with Hilt?

Use KSP for new projects. Dagger's documentation says its KSP support is stable from Dagger 2.60 with KSP 2.3.9 or newer, and Google's Hilt setup guide uses KSP. kapt still works but is slower.

Where is hiltViewModel() now?

Since androidx.hilt 1.3.0 it lives in the artifact androidx.hilt:hilt-lifecycle-viewmodel-compose and the package androidx.hilt.lifecycle.viewmodel.compose. The old androidx.hilt.navigation.compose version is deprecated.

What is the difference between @Binds and @Provides?

@Binds tells Hilt which implementation to use for an interface and goes on an abstract function. @Provides is a function with a body that builds an object yourself, which you need for types you cannot add @Inject to, such as SharedPreferences or a Retrofit service.

Do I need Hilt for a small app?

No. Manual dependency injection with a simple container class works well for small apps. Hilt pays off as the number of screens, repositories and tests grows, because it removes the boilerplate and makes swapping fakes in tests easy.

Sources

APIs and versions checked against the official Android, Dagger and KSP pages on November 30, 2026 (Hilt 2.60.1, androidx.hilt 1.4.0, KSP 2.3.14).

What to Try Next

Keep learning Android

Head back to the Android with Kotlin track for the full learning path and more hands-on projects.

Back to the Android Track