Skip to content

Commit f9395fb

Browse files
authored
Allow a @Nullable value for the second parameter of requireNonNullElse.
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)
1 parent 45aebb1 commit f9395fb

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

src/java.base/share/classes/java/util/Objects.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ public static boolean nonNull( @Nullable Object obj) {
319319
* {@code defaultObj} is {@code null}
320320
* @since 9
321321
*/
322-
public static <T> T requireNonNullElse(@Nullable T obj, T defaultObj) {
322+
public static <T> T requireNonNullElse(@Nullable T obj, @Nullable T defaultObj) {
323323
return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
324324
}
325325

0 commit comments

Comments
 (0)