11

Is it possible to optionally inject a value in dagger 2? In particular, I want to do something like this.

@Inject A(Optional<B> b) {
  this.b = b;
}

If B is undefined in the modules, I would want dagger to give an Optional.empty(), If it is defined then give Optional.of(value).

Is this doable or do I need a module that defines those optional values?

Cogman
  • 2,070
  • 19
  • 36

2 Answers2

10

Optional injection requires a module to add an optional binding to your component as Dagger requires every dependency, even an explicitly missing one, on the dependency graph. When you want to fulfill this optional with an implemention you will add an impl binding module to a component, normally a subcomponent, which wants to fulfill it.

The following is a what a Module should look like:

@Module
public interface OptionalModule {
  @BindsOptionalOf
  Foo bindOptionalFoo();
}

and

@Module
public interface ImplModule {
  @Binds
  Foo bindFooImpl(FooImpl foo);
}

Then you can constructor or member inject Optional

public class Bar {
  @Inject
  public Bar(Optional<Foo> optionalFoo) {}
}

or

public class Bar {
  @Inject
  public Optional<Foo> optionalFoo;
}
MinceMan
  • 7,483
  • 3
  • 38
  • 40
  • How would I incorporate conditional-providing in this? For e.g.: ``` @Module public interface ImplModule { @Provides Foo provideFooImpl() { if (someCondition) { return impl; } else { return Optional.empty(); } } } ``` – Daksh Nov 19 '22 at 21:23
1

You are looking for @BindsOptionalOf.

Corey G
  • 7,754
  • 1
  • 28
  • 28