google / google/guice

Optional<X> and value binding inside createChildInjector fails

Open
#1,165 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
12.7k
Forks
1.7k
Avg merge
11m
Merged PRs (30d)
2

Description

Just wondered whether this is a supported scenario of using Optional -- it doesn't work, but it doesn't fail either. If I create an optional binding in a module and a provider that depends on this binding, say:
```
private static class ModuleImpl implements Module {
@Override
public void configure(Binder binder) {
OptionalBinder.newOptionalBinder(binder, Integer.class);
binder.requireExplicitBindings();
}

@Provides
String provide(Optional optional) {
return optional.toString();
}
}
```

Then if I bind this value within the same injector, as here:

```
Injector injector = Guice.createInjector(new ModuleImpl(),
(binder) -> {
binder.bind(Integer.class).toInstance(42);
});

Assertions.assertThat(injector.getInstance(String.class)).isEqualTo("Optional.of(42)");
```
Then everything works. However, if I bind it in a child injector, as here:

```
@Test
public void testBindingInChild() {
Injector injector = Guice.createInjector(new ModuleImpl())
.createChildInjector(
(binder) -> {
binder.bind(Integer.class).toInstance(42);
});

Assertions.assertThat(injector.getInstance(String.class)).isEqualTo("Optional.of(32)");
}
```

Things no longer work -- the returned value is Optional.absent() (and the optional doesn't resolve).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.