From f9395fb527509cb0cd71eda0769e26f7fbab80f8 Mon Sep 17 00:00:00 2001 From: Chris Povirk Date: Mon, 5 Jun 2023 13:15:57 -0400 Subject: [PATCH] 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) --- src/java.base/share/classes/java/util/Objects.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/java.base/share/classes/java/util/Objects.java b/src/java.base/share/classes/java/util/Objects.java index 12f3d297843..7af6b538973 100644 --- a/src/java.base/share/classes/java/util/Objects.java +++ b/src/java.base/share/classes/java/util/Objects.java @@ -319,7 +319,7 @@ public static boolean nonNull( @Nullable Object obj) { * {@code defaultObj} is {@code null} * @since 9 */ - public static T requireNonNullElse(@Nullable T obj, T defaultObj) { + public static T requireNonNullElse(@Nullable T obj, @Nullable T defaultObj) { return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj"); }