Skip to content

Commit

Permalink
Allow a @Nullable value for the second parameter of `requireNonNull…
Browse files Browse the repository at this point in the history
…Else`.

The existing approach follows the Checker Framework philosophy, under
which passing `null` for a `@Nullable` parameter should never lead to a
`NullPointerException`. (Compare `Method.invoke`, whose "receiver" _and_
"arguments" parameters are declared as non-nullable by the Checker
Framework, even though some callers _can_ pass `null` for the "receiver"
and some _must_ pass `null` for some of the arguments.)

The JSpecify thinking has moved in the direction of saying that, if
`null` should ever be permitted for a parameter, then the parameter
should be declared with a type that includes `null`. And we know that
many callers pass `null` for the second parameter. Here's an imaginary
such caller:

```java
for (Key key : union(map1.keySet(), map2.keySet()) {
  Value value = requireNonNullElse(map1.get(key), map2.get(key));
}
```

(We could consider making a similar change to `requireNonNullElseGet`.
But it's rarely used, and perhaps no one wants to pass a `Supplier` that
may return `null`, anyway. So I'm happy to leave it alone for now or to
change it if that's more palatable.)

(#11)
  • Loading branch information
cpovirk authored Jun 5, 2023
1 parent 45aebb1 commit f9395fb
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion src/java.base/share/classes/java/util/Objects.java
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ public static boolean nonNull( @Nullable Object obj) {
* {@code defaultObj} is {@code null}
* @since 9
*/
public static <T> T requireNonNullElse(@Nullable T obj, T defaultObj) {
public static <T> T requireNonNullElse(@Nullable T obj, @Nullable T defaultObj) {
return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}

Expand Down

0 comments on commit f9395fb

Please # to comment.