RFR 8071670: java.util.Optional: please add a way to specify if-else behavior
Daniel Fuchs
daniel.fuchs at oracle.com
Thu Feb 12 14:50:06 UTC 2015
Hi Paul,
This looks good - I have noticed one copy/paste error in the javadoc
though:
OptionalInt.java:
looks like the throws clause of ifPresent and ifPresentOrElse have been
interverted:
138 * @throws NullPointerException if a value is present and
{@code action} is
139 * null, or a value is not present and {@code emptyAction} is
null.
140 */
141 public void ifPresent(IntConsumer action) {
142 if (isPresent) {
143 action.accept(value);
144 }
145 }
146
147 /**
148 * If a value is present, perform the given action with the value,
149 * otherwise perform the given empty-based action.
150 *
151 * @param action the action to be performed if a value is present
152 * @param emptyAction the empty-based action to be performed
if a value is
153 * not present
154 * @throws NullPointerException if value is present and {@code
action} is
155 * null
156 * @since 1.9
157 */
158 public void ifPresentOrElse(IntConsumer action, Runnable
emptyAction) {
Concerning the test, should there be a test that verifies that NPE
is thrown when null is passed - as specified in the javadoc?
Best regards,
-- daniel
On 03/02/15 16:38, Paul Sandoz wrote:
> Hi,
>
> http://cr.openjdk.java.net/~psandoz/jdk9/JDK-8071670-Optional-ifPresentOrElse/webrev/
>
> Here is another tweak to Optional (and primitives) that has some weight:
>
> /**
> * If a value is present, perform the given action with the value,
> * otherwise perform the given empty-based action.
> *
> * @param action the action to be performed if a value is present
> * @param emptyAction the empty-based action to be performed if a value is
> * not present
> * @throws NullPointerException if a value is present and {@code action} is
> * null, or a value is not present and {@code emptyAction} is null.
> * @since 1.9
> */
> public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
> if (value != null) {
> action.accept(value);
> } else {
> emptyAction.run();
> }
> }
>
> (In hindsight we should have been consistent and thrown NPEs regardless of the optional state. The exception throwing behaviour is consistent with ifPresent.)
>
> Previously it was kind of awkward if one had two lambdas or method refs handy, one had to do:
>
> o.ifPresent(v -> ...);
> if (!o.ifPresent()) {
> ...
> }
>
> Or just:
>
> if (o.ifPresent()) {
> ...
> } else {
> ...
> }
>
>
> I also updated the language of the ifPresent methods to be more consistent with Collection/Stream.forEach.
>
> Paul.
>
More information about the core-libs-dev
mailing list