Prem
Prem

Reputation: 3543

Dagger2 component generic inject method

I converted my app from Dagger1.0 to dagger2.0, and have an app component with many void inject(Activity/Fragment/Receiver/etc object) methods.

With dagger 1.0 I just could just do objectGraph.inject(Object object) but now my component has to have a method for every single class that gets dependencies injected to it.

Why can't I just have a component that has one method: <T> void inject(T t); ?

For reference: My component right now:


public interface AppComponent {

    void inject(MyFirstActivity activity);

    void inject(MySecondActivity activity);

    void inject(MyFirstFragment fragment);

    void inject(MySecondFragment fragment);

    ...
}

The component I want:


public interface AppComponent {
   <T> void inject(T object);
}

Upvotes: 8

Views: 1236

Answers (1)

David Medenjak
David Medenjak

Reputation: 34532

Why can't I just have a component that has one method: <T> void inject(T t);?

Because dagger-2 uses code generation and needs to know the type information at compile time. Without it, there is no way to tell which dependencies T would need—therefore code generation would be impossible.

If you compile your first component and check out the generated Dagger*Component source code, you will see that each inject method gets its own factory method, providing all of the dependencies for the given type.

This is the same for injecting subclasses. You can check out the paragraph A note about covariance in the component documentation. Because the superclass type is known, dagger can inject members in the superclass, but it will not inject members of potential subtypes. Again, because dagger-2 relies on compile time code generation this is not possible.

Upvotes: 6

Related Questions