Skip to content

Commit 6688819

Browse files
eamonnmcmanusGoogle Java Core Libraries
authored and
Google Java Core Libraries
committed
Clarify that Optional values can be set from @Nullable parameters.
This was not all that clear from the documentation. If you have `Optional<String> getFoo()` property then you can set it with `setFoo(String)` _or_ `setFoo(@nullable String)`. In the first case, you'll get an exception if the parameter is null, but in the second it will work, and `foo` will be `Optional.empty()`. Also add a test that checks that you do indeed get an exception without `@Nullable`. RELNOTES=n/a PiperOrigin-RevId: 375607596
1 parent f00c32a commit 6688819

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1672,6 +1672,13 @@ public void testOmitOptionalWithBuilder() {
16721672
.build();
16731673
assertThat(suppliedDirectly.optionalString()).hasValue("foo");
16741674
assertThat(suppliedDirectly.optionalInteger()).hasValue(23);
1675+
1676+
try {
1677+
// The parameter is not marked @Nullable so this should fail.
1678+
OptionalPropertiesWithBuilder.builder().setOptionalString((String) null);
1679+
fail();
1680+
} catch (NullPointerException expected) {
1681+
}
16751682
}
16761683

16771684
@AutoValue

value/userguide/builders-howto.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,8 @@ property of type `Optional<String>`, say, then it will default to an empty
311311
`Optional` without needing to [specify](#default) a default explicitly. And,
312312
instead of or as well as the normal `setFoo(Optional<String>)` method, you can
313313
have `setFoo(String)`. Then `setFoo(s)` is equivalent to
314-
`setFoo(Optional.of(s))`.
314+
`setFoo(Optional.of(s))`. (If it is `setFoo(@Nullable String)`, then `setFoo(s)`
315+
is equivalent to `setFoo(Optional.ofNullable(s))`.)
315316

316317
Here, `Optional` means either [`java.util.Optional`] from Java (Java 8 or
317318
later), or [`com.google.common.base.Optional`] from Guava. Java 8 also

0 commit comments

Comments
 (0)