Junior — Middle
What annotations in Hilt are used to include classes in the dependency graph?
sobes.tech AI
Answer from AI
In Hilt, the following main annotations are used to include classes in the dependency graph:
-
@Inject— marks a constructor, field, or method so that Hilt can provide the dependency. -
@Module— indicates a class that provides dependencies through methods annotated with@Provides. -
@InstallIn— specifies which component (e.g., SingletonComponent, ActivityComponent) the module is installed into. -
@Singletonand other scopes — define the lifetime of the dependency.
Example:
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideApiService(): ApiService {
return Retrofit.Builder()
.baseUrl("https://example.com")
.build()
.create(ApiService::class.java)
}
}
class Repository @Inject constructor(private val apiService: ApiService) {
// ...
}
Thus, @Inject and @Module with @InstallIn are key annotations for including classes in Hilt's dependency graph.