Hilt Scopes & Components Interview Questions
ARCHITECTURE › Dependency Injection
What are Hilt components, and which ones come built in?
What a strong answer covers: Components are containers with a lifetime that hold bindings. SingletonComponent (application), ActivityRetainedComponent (survives configuration changes), ViewModelComponent, ActivityComponent, FragmentComponent, ViewComponent, ViewWithFragmentComponent and ServiceComponent. Child components can use their parents' bindings.
What does a scope annotation like @Singleton or @ActivityScoped actually do?
What a strong answer covers: A scope makes the component return the same instance for every request within that component's lifetime. Without a scope, every injection gets a new instance. @Singleton means one per application; @ActivityScoped one per activity instance; @ViewModelScoped one per ViewModel. A scope must match the module's component.
Why shouldn't you make everything @Singleton?
What a strong answer covers: Singletons live as long as the process: they hold memory forever, they can accidentally hold onto shorter-lived objects like activities (leaks), they share mutable state across screens, causing bugs, and scoped bindings are slightly more expensive (thread-safe double-checked access). Only scope things that must be shared or are expensive to create, like OkHttpClient or a database.
What's the difference between ActivityRetainedComponent and ActivityComponent, and when would you use ViewModelScoped?
What a strong answer covers: ActivityRetainedComponent lives across configuration changes, like a ViewModel, so its scoped objects survive rotation; ActivityComponent is destroyed and recreated with the activity, so it can hold activity references. @ViewModelScoped gives one instance per ViewModel, shared by everything injected into that ViewModel, such as a use case holding screen-level state.
How would you create a custom Hilt component, for example one that lives while the user is logged in, and what are the pitfalls?
What a strong answer covers: Define a @DefineComponent(parent = SingletonComponent::class) interface with a custom scope like @LoggedInScope and a builder; a singleton manager creates the component at login and drops it at logout, and you reach its bindings through entry points. Pitfalls: Android entry points can't inject from it directly, you must handle the component not existing, and objects that outlive logout can still hold old user data. Many teams use a simpler session object or clear data at logout instead.