skip to content

Hilt

Dagger-based injection wired to Android lifecycles through @HiltAndroidApp, @AndroidEntryPoint and @InstallIn. Interviewers ask because its compile-time errors only make sense once you see the graph.

on this pageshow

explore

questions

6

In Hilt, what do @HiltAndroidApp and @AndroidEntryPoint do, and what fails when an injected fragment's host activity lacks @AndroidEntryPoint?

level: juniorimportance: must knowfreq 80%

answer

  1. generated Hilt_ base classes
  2. Application holds the root component
  3. fields filled in super.onCreate()
  4. components nest: activity, then fragment
  5. runtime check on the fragment's host

basics

~20 s

@HiltAndroidApp on the Application triggers Hilt's code generation and holds the app-wide SingletonComponent; @AndroidEntryPoint makes an activity, fragment, view, service or receiver injectable. A Hilt fragment inside a non-Hilt activity throws IllegalStateException when it is attached.

solid answer

~40 s

`@HiltAndroidApp` goes on the `Application` class. It triggers generation of the Hilt components and a `Hilt_NewsApplication` base class that creates the root `SingletonComponent` and injects the application's own fields in `super.onCreate()`; the Hilt Gradle plugin swaps in that base class for you. `@AndroidEntryPoint` does the same job for an activity, fragment, view, service or broadcast receiver: the generated base class attaches it to the right component at the right lifecycle point and fills its non-private `@Inject` fields, in `super.onCreate()` for an activity. Components nest, so a fragment's component is built from its activity's: a Hilt fragment hosted by an activity without `@AndroidEntryPoint` fails at runtime with "Hilt Fragments must be attached to an @AndroidEntryPoint Activity". The same check one level up catches an application class missing from the manifest's `android:name`.

code

kotlin · 26 lines
kotlin
@HiltAndroidApp
class NewsApplication : Application()

class ReadingAnalytics @Inject constructor() {
    fun screenOpened(name: String) {
        Log.d("ReadingAnalytics", "opened $name")
    }
}

class ThumbnailLoader @Inject constructor()

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject lateinit var analytics: ReadingAnalytics

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState) // injection happens here
        analytics.screenOpened("home")
    }
}

// Its host activity must also be @AndroidEntryPoint
@AndroidEntryPoint
class ArticleListFragment : Fragment() {
    @Inject lateinit var thumbnails: ThumbnailLoader
}

go deeper

for a junior

Recall which annotation goes on the Application and which on activities and fragments, and that injected fields are usable after super.onCreate().

for a middle

Explain the generated Hilt_ base classes, what the Gradle plugin rewrites, and why a fragment's component must be built from a Hilt activity's component.

for a senior

Diagnose the two attach-time IllegalStateExceptions from their messages, and explain why the host rule can only be checked at runtime.

for a principal

Frame entry points as the boundary where framework-created objects join the graph, and decide which framework classes a codebase should let inject fields at all.

## What the two annotations generate Hilt is the Android layer over Dagger: you never write or instantiate a component yourself. Instead you mark the Android classes that should receive dependencies, and Hilt generates the plumbing. - **`@HiltAndroidApp`** goes on exactly one class, your `Application` subclass. It is the signal to generate **all** of the app's Hilt components, because, as its own documentation puts it, all components are built in the same compilation as the annotated application. Every Hilt module and entry point therefore has to be a transitive compile dependency of the Gradle module that holds this class. - It also generates a base class named `Hilt_<YourApplication>`. That base class creates the root **`SingletonComponent`** and injects the application's own `@Inject` fields inside `super.onCreate()`. - **`@AndroidEntryPoint`** marks an activity, fragment, view, service or broadcast receiver. It generates a `Hilt_<ClassName>` base class that obtains the matching component at the right point in the lifecycle and injects the class's `@Inject` fields. - With the **Hilt Gradle plugin**, you keep writing `class MainActivity : AppCompatActivity()`; the plugin rewrites the superclass to the generated one. Without the plugin you pass the original base class to the annotation and extend `Hilt_MainActivity` by hand. ## Which classes can be entry points | Android class | Annotation | Component used to inject it | Fields ready | |---|---|---|---| | `Application` | `@HiltAndroidApp` | `SingletonComponent` | in `super.onCreate()` | | Activity (a `ComponentActivity`) | `@AndroidEntryPoint` | `ActivityComponent` | in `super.onCreate()` | | AndroidX `Fragment` | `@AndroidEntryPoint` | `FragmentComponent` | component created in `onAttach()` | | `View` | `@AndroidEntryPoint` | `ViewComponent` (or `ViewWithFragmentComponent`) | component created in the view's constructor | | `Service` | `@AndroidEntryPoint` | `ServiceComponent` | in `super.onCreate()` | | `BroadcastReceiver` | `@AndroidEntryPoint` | no component of its own: injected from `SingletonComponent` | in `onReceive()` | Hilt supports only activities that extend `ComponentActivity`, such as `AppCompatActivity`, and only AndroidX fragments. In a Compose app you do not annotate composables at all: you annotate the root activity, and screens obtain their ViewModels through Hilt's ViewModel support. Plain classes need none of this. A repository with an `@Inject constructor` is simply a binding Hilt knows how to build; only the classes the Android framework instantiates need an entry-point annotation, because Hilt cannot call their constructors. ## The host rule: components nest Hilt's components form a hierarchy: `SingletonComponent` is the root, `ActivityRetainedComponent` and `ActivityComponent` sit below it, and `FragmentComponent` is a child of `ActivityComponent`. A fragment's component is therefore created **from its host activity's component**, which is what lets a fragment inject activity-level bindings. The consequence is a runtime rule. When a Hilt fragment is attached, the generated code checks that the host is a Hilt activity, and if it is not, it throws `IllegalStateException` with the message "Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: ...". The compiler cannot catch this, because which activity hosts which fragment is only known at runtime. The same pattern repeats one level up: a Hilt activity whose application is not the `@HiltAndroidApp` class fails with "Hilt Activity must be attached to an @HiltAndroidApp Application", and when the application object is a plain `Application`, the message asks whether you forgot the `android:name` attribute on `<application>` in the manifest. ## Field injection rules 1. Injected fields **cannot be private**: the generated code outside your class assigns them, so Hilt reports a compile error for a private field. In Kotlin, write `@Inject lateinit var`. 2. Fields are injected **during `super.onCreate()`** in an activity, so reading them in a property initializer or before that call sees an uninitialized `lateinit` property. 3. An **abstract** base class with its own `@Inject` fields does not need `@AndroidEntryPoint`; annotate the concrete subclasses and the base class's fields are injected with them. 4. Each activity instance gets its own `ActivityComponent` instance; the same is true per fragment instance. ## Diagnosing a setup failure - **Crash on the first screen with the `@HiltAndroidApp` message**: check the manifest's `android:name` and that the annotated class is the one declared. - **Crash when a fragment is added**: find the host activity in the message and annotate it, or move the fragment to a Hilt activity. - **`lateinit property has not been initialized`** in an activity: something read the field before `super.onCreate()`. - **A compile error on a field**: it is private, or no binding exists for its type; constructor-inject the type or provide it from a module.

  • Why does Hilt refuse to inject a private @Inject field?
    Field injection is done by generated code that lives outside your class and assigns the field directly. It cannot reach a private field, so Hilt reports a compile error instead of falling back to reflection. In Kotlin the idiom is a non-private `@Inject lateinit var`.
  • A BaseActivity shared by several screens declares its own @Inject fields; does it need @AndroidEntryPoint?
    Not if it is abstract. Annotate each concrete activity with `@AndroidEntryPoint`; Hilt injects the inherited fields of an abstract base class along with the subclass's own. Putting the annotation on the concrete classes keeps one generated base class per real screen.
  • In a Compose app, which classes get @AndroidEntryPoint?
    The root `ComponentActivity`, not the composables. It is the single entry point for the UI hierarchy; screens obtain Hilt ViewModels with `hiltViewModel()` and receive everything else through those ViewModels. Services, receivers and any remaining fragments still carry their own annotation.

  • Every class with an @Inject constructor also needs @AndroidEntryPoint.
  • @HiltAndroidApp can go on the launcher activity instead of the Application.
  • A Hilt fragment works in any activity because it has its own component.
  • Injected fields are already set before super.onCreate() is called.
  • Hilt fields may be private because Hilt injects them by reflection.
  • A missing @AndroidEntryPoint on the host activity is caught at compile time.
open as a page

In a Hilt module, when do you use @Binds versus @Provides, and how does @InstallIn decide where those bindings can be injected?

level: middleimportance: must knowfreq 78%

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.

open as a page

With Hilt, how does an Android screen obtain a @HiltViewModel, and why is injecting that ViewModel into an @Inject field rejected?

level: middleimportance: must knowfreq 75%

basics

~20 s

Annotate the ViewModel with @HiltViewModel and an @Inject constructor, then request it through the ViewModel APIs: by viewModels() in an @AndroidEntryPoint activity or fragment, or hiltViewModel() in Compose. Field injection fails the build because it bypasses the ViewModelStore.

open as a page

In Hilt, which scope fits an article cache shared by the ViewModels of one reader activity that must survive rotation, and why not @ActivityScoped or @Singleton?

level: seniorimportance: must knowfreq 62%

basics

~20 s

@ActivityRetainedScoped: ActivityRetainedComponent survives configuration changes and ends when the activity finishes, and ViewModels can see it. @ActivityScoped is rebuilt on every rotation, losing the cache; @Singleton keeps it for the whole process and shares it across every reader screen.

open as a page

In Hilt, how do you inject dependencies into a WorkManager worker and into a ContentProvider, two classes Hilt does not instantiate?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A worker gets @HiltWorker and an @AssistedInject constructor with @Assisted Context and WorkerParameters, and WorkManager is configured with the injected HiltWorkerFactory. A ContentProvider declares an @EntryPoint interface installed in SingletonComponent and reads it through EntryPointAccessors.fromApplication().

open as a page

In Hilt instrumented tests, how do you swap the production network module for a fake, and when is @UninstallModules better than @TestInstallIn?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Mark the test @HiltAndroidTest, run HiltAndroidRule first on HiltTestApplication, and add an androidTest module annotated @TestInstallIn that replaces the network module. Use @UninstallModules with a nested module or @BindValue only when one test class needs a different fake.

open as a page