In a Hilt module, when do you use @Binds versus @Provides, and how does @InstallIn decide where those bindings can be injected?
answer
- interface versus a type you construct
- abstract method, no body
- body runs on every request
- visible in the component and below
- a module does not scope its bindings
basics
~20 s@Binds is an abstract method mapping an interface to an implementation Hilt can already build; @Provides has a body that constructs the instance, for third-party or builder-made types. @InstallIn names the Hilt component: bindings are visible there and in its child components.
solid answer
~50 sUse `@Binds` when the type is an interface and its implementation already has an `@Inject` constructor: an abstract method whose return type is the interface and whose single parameter is the implementation. Use `@Provides` when you must run code to get the instance, for a class you do not own, such as an `OkHttpClient` or a Retrofit service, or one made with a builder; its parameters are dependencies and its body runs each time the binding is requested unless the method is scoped. Dagger's own documentation says to prefer `@Binds` where both fit, because the generated code is likely more efficient. Every Hilt module also needs `@InstallIn`, which names the component the module joins: its bindings can be injected in that component and every component below it, never above. A scope annotation on a binding must match that component, and leaving it off means unscoped.
code
kotlin · 43 lines@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class NewsHttpClient
interface NewsApi {
@GET("headlines")
suspend fun headlines(): ResponseBody
}
interface NewsRepository {
suspend fun headlinesJson(): String
}
class DefaultNewsRepository @Inject constructor(
private val api: NewsApi
) : NewsRepository {
override suspend fun headlinesJson(): String = api.headlines().string()
}
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
@NewsHttpClient
fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder().build()
@Provides
@Singleton
fun provideNewsApi(@NewsHttpClient client: OkHttpClient): NewsApi =
Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(client)
.build()
.create(NewsApi::class.java)
}
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
abstract fun bindNewsRepository(impl: DefaultNewsRepository): NewsRepository
}go deeper
Know that @Binds maps an interface to an implementation and @Provides builds a type with code, and that every Hilt module carries @InstallIn.
Explain the abstract-method shape of @Binds, the body-runs-per-request rule of @Provides, and how a component's bindings are visible only to it and its descendants.
Read a missing-binding error as a module installed too low, and keep scope annotations matched to the module's component rather than scoping by habit.
Set a team convention for module layout, qualifier usage and what may be scoped, so a growing graph stays predictable and cheap to build.
## Why Hilt needs modules at all Hilt learns how to build most types from an **`@Inject` constructor**: the constructor's parameters are the type's dependencies. Two kinds of type cannot be described that way. An **interface** has no constructor, and a **class you do not own**, such as `OkHttpClient`, a Retrofit service or a Room database, cannot be annotated, and is often made through a builder. A **Hilt module** is a class annotated with `@Module` that gives Hilt this missing binding information. A Hilt module is unrelated to a Gradle module. ## `@Binds`: delegate an interface to an implementation A `@Binds` method is **abstract**, so it lives in an abstract class or interface. Its **return type** is the type being bound, usually an interface, and its **single parameter** is the implementation to use. The implementation must itself be something Hilt can build, normally through its own `@Inject` constructor. - There is no body: you are telling Hilt that a request for `NewsRepository` should be satisfied by `DefaultNewsRepository`. - Dagger's javadoc calls `@Binds` a drop-in replacement for a `@Provides` method that simply returns an injected parameter, and recommends it because the generated implementation is likely to be more efficient. - A `@Binds` method may carry a scope or a qualifier. ## `@Provides`: run code to produce an instance A `@Provides` method has a body. In Kotlin it usually sits in an `object` module. - The **return type** says what is provided, the **parameters** are its dependencies, and the **body** builds it. - Hilt runs the body **every time** the binding is requested, unless the method carries a scope annotation such as `@Singleton`. - It is the only option for third-party types and for anything that needs configuration, like a client with interceptors and timeouts. Because `@Binds` methods must be abstract and Kotlin `@Provides` methods are usually concrete, teams typically keep two modules: an abstract `RepositoryModule` of `@Binds` methods and an `object NetworkModule` of `@Provides` methods. | | `@Binds` | `@Provides` | |---|---|---| | Method shape | abstract, one parameter | concrete, any parameters | | Module shape | abstract class or interface | `object` (or class) | | Typical use | interface to an `@Inject` implementation | third-party or builder-made type | | Runs your code | no | yes, on each unscoped request | ## `@InstallIn`: which component, and who can see it Every Hilt module must also carry **`@InstallIn`**, naming one or more components, normally Hilt's predefined ones: `SingletonComponent`, `ActivityRetainedComponent`, `ViewModelComponent`, `ActivityComponent`, `FragmentComponent`, `ViewComponent`, `ViewWithFragmentComponent` or `ServiceComponent`. 1. A binding installed in a component can be injected **in that component and every descendant**. A binding in `SingletonComponent` is available everywhere; one in `ActivityComponent` is available to activities, their fragments and views, but not to a ViewModel or a service. 2. A parent never sees a child's bindings. A `@Singleton` class cannot depend on something installed only in `ActivityComponent`; Dagger reports a missing binding at compile time. 3. If a `@Module` lacks `@InstallIn`, Hilt raises a **compile error** by default, because a module nobody installs is silently ignored otherwise. The check can be relaxed during a migration with `@DisableInstallInCheck` or a compiler flag. 4. **Installing is not scoping.** Every binding in a module is unscoped unless the method itself carries a scope annotation, and that scope must match the component: a binding in an `@InstallIn(ActivityComponent::class)` module may only be `@ActivityScoped`. ## Qualifiers: two bindings of one type When you need two `OkHttpClient` instances, say one with an auth interceptor, you declare a **qualifier**, an annotation marked `@Qualifier`, and put it on both the `@Provides` method and every injection site. The Android guide's advice is to qualify every binding of that type rather than leaving a bare default one, because a bare one is easy to inject by mistake. Hilt also predefines two qualifiers for `Context`: **`@ApplicationContext`**, available everywhere, and **`@ActivityContext`**, available only in `ActivityComponent` and below. ## Common mistakes - Writing a `@Provides` method that only returns its parameter, where `@Binds` says the same thing. - Expecting a `@Binds` to work when the implementation has no `@Inject` constructor or binding of its own. - Assuming everything in a `SingletonComponent` module is a singleton. - Installing a module low, in `ActivityComponent`, then trying to inject its binding into a ViewModel.
- DefaultNewsRepository is bound with an unscoped @Binds; is the repository a singleton?No. An unscoped `@Binds` hands out whatever the implementation's own binding produces, and an unscoped `@Inject` constructor means a new instance per request. To share one instance, annotate the `@Binds` method with `@Singleton` in a `SingletonComponent` module, or annotate the implementation class itself with `@Singleton`.
- You install a module in ActivityComponent and inject its binding into a @HiltViewModel; what happens?The build fails with a missing binding. A ViewModel is injected from `ViewModelComponent`, whose parent is `ActivityRetainedComponent`, so it cannot see `ActivityComponent`. Install the module in `ViewModelComponent` or higher, which also keeps activity-bound objects out of the ViewModel.
- Why does Hilt insist on @InstallIn when plain Dagger does not?Hilt has no component interface where you list modules; `@InstallIn` is how a module joins a predefined component. A module without it would never be installed and would be very hard to debug, so Hilt fails the build. `@DisableInstallInCheck` exists for migrations.
- @Binds can construct a class that has no @Inject constructor.
- Every binding in a SingletonComponent module is automatically a singleton.
- A @Provides method runs once and is then cached by Hilt.
- A module in ActivityComponent can be injected into a @Singleton class.
- @InstallIn is optional; Hilt finds every @Module on the classpath anyway.
- @Binds and @Provides are interchangeable for an OkHttpClient built with a builder.