1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util;
  26 
  27 import java.util.function.DoubleConsumer;
  28 import java.util.function.DoubleSupplier;
  29 import java.util.function.Supplier;
  30 
  31 /**
  32  * A container object which may or may not contain a {@code double} value.
  33  * If a value is present, {@code isPresent()} will return {@code true} and
  34  * {@code get()} will return the value.
  35  *
  36  * <p>Additional methods that depend on the presence or absence of a contained
  37  * value are provided, such as {@link #orElse(double) orElse()}
  38  * (return a default value if value not present) and
  39  * {@link #ifPresent(java.util.function.DoubleConsumer) ifPresent()} (execute a block
  40  * of code if the value is present).
  41  *
  42  * @since 1.8
  43  */
  44 public final class OptionalDouble {
  45     /**
  46      * Common instance for {@code empty()}.
  47      */
  48     private static final OptionalDouble EMPTY = new OptionalDouble();
  49 
  50     /**
  51      * If true then the value is present, otherwise indicates no value is present
  52      */
  53     private final boolean isPresent;
  54     private final double value;
  55 
  56     /**
  57      * Construct an empty instance.
  58      *
  59      * @implNote generally only one empty instance, {@link OptionalDouble#EMPTY},
  60      * should exist per VM.
  61      */
  62     private OptionalDouble() {
  63         this.isPresent = false;
  64         this.value = Double.NaN;
  65     }
  66 
  67     /**
  68      * Returns an empty {@code OptionalDouble} instance.  No value is present for this
  69      * OptionalDouble.
  70      *
  71      * @apiNote Though it may be tempting to do so, avoid testing if an object
  72      * is empty by comparing with {@code ==} against instances returned by
  73      * {@code Option.empty()}. There is no guarantee that it is a singleton.
  74      * Instead, use {@link #isPresent()}.
  75      *
  76      *  @return an empty {@code OptionalDouble}.
  77      */
  78     public static OptionalDouble empty() {
  79         return EMPTY;
  80     }
  81 
  82     /**
  83      * Construct an instance with the value present.
  84      *
  85      * @param value the double value to be present.
  86      */
  87     private OptionalDouble(double value) {
  88         this.isPresent = true;
  89         this.value = value;
  90     }
  91 
  92     /**
  93      * Return an {@code OptionalDouble} with the specified value present.
  94      *
  95      * @param value the value to be present
  96      * @return an {@code OptionalDouble} with the value present
  97      */
  98     public static OptionalDouble of(double value) {
  99         return new OptionalDouble(value);
 100     }
 101 
 102     /**
 103      * If a value is present in this {@code OptionalDouble}, returns the value,
 104      * otherwise throws {@code NoSuchElementException}.
 105      *
 106      * @return the value held by this {@code OptionalDouble}
 107      * @throws NoSuchElementException if there is no value present
 108      *
 109      * @see OptionalDouble#isPresent()
 110      */
 111     public double getAsDouble() {
 112         if (!isPresent) {
 113             throw new NoSuchElementException("No value present");
 114         }
 115         return value;
 116     }
 117 
 118     /**
 119      * Return {@code true} if there is a value present, otherwise {@code false}.
 120      *
 121      * @return {@code true} if there is a value present, otherwise {@code false}
 122      */
 123     public boolean isPresent() {
 124         return isPresent;
 125     }
 126 
 127     /**
 128      * Have the specified consumer accept the value if a value is present,
 129      * otherwise do nothing.
 130      *
 131      * @param consumer block to be executed if a value is present
 132      * @throws NullPointerException if value is present and {@code consumer} is
 133      * null
 134      */
 135     public void ifPresent(DoubleConsumer consumer) {
 136         if (isPresent)
 137             consumer.accept(value);
 138     }
 139 
 140     /**
 141      * Return the value if present, otherwise return {@code other}.
 142      *
 143      * @param other the value to be returned if there is no value present
 144      * @return the value, if present, otherwise {@code other}
 145      */
 146     public double orElse(double other) {
 147         return isPresent ? value : other;
 148     }
 149 
 150     /**
 151      * Return the value if present, otherwise invoke {@code other} and return
 152      * the result of that invocation.
 153      *
 154      * @param other a {@code DoubleSupplier} whose result is returned if no value
 155      * is present
 156      * @return the value if present otherwise the result of {@code other.getAsDouble()}
 157      * @throws NullPointerException if value is not present and {@code other} is
 158      * null
 159      */
 160     public double orElseGet(DoubleSupplier other) {
 161         return isPresent ? value : other.getAsDouble();
 162     }
 163 
 164     /**
 165      * Return the contained value, if present, otherwise throw an exception
 166      * to be created by the provided supplier.
 167      *
 168      * @apiNote A method reference to the exception constructor with an empty
 169      * argument list can be used as the supplier. For example,
 170      * {@code IllegalStateException::new}
 171      *
 172      * @param <X> Type of the exception to be thrown
 173      * @param exceptionSupplier The supplier which will return the exception to
 174      * be thrown
 175      * @return the present value
 176      * @throws X if there is no value present
 177      * @throws NullPointerException if no value is present and
 178      * {@code exceptionSupplier} is null
 179      */
 180     public<X extends Throwable> double orElseThrow(Supplier<X> exceptionSupplier) throws X {
 181         if (isPresent) {
 182             return value;
 183         } else {
 184             throw exceptionSupplier.get();
 185         }
 186     }
 187 
 188     /**
 189      * Indicates whether some other object is "equal to" this Optional. The
 190      * other object is considered equal if:
 191      * <ul>
 192      * <li>it is also an {@code OptionalInt} and;
 193      * <li>both instances have no value present or;
 194      * <li>the present values are "equal to" each other via {@code Double.compare() == 0}.
 195      * </ul>
 196      *
 197      * @param obj an object to be tested for equality
 198      * @return {code true} if the other object is "equal to" this object
 199      * otherwise {@code false}
 200      */
 201     @Override
 202     public boolean equals(Object obj) {
 203         if (this == obj) {
 204             return true;
 205         }
 206 
 207         if (!(obj instanceof OptionalDouble)) {
 208             return false;
 209         }
 210 
 211         OptionalDouble other = (OptionalDouble) obj;
 212         return (isPresent && other.isPresent)
 213                ? Double.compare(value, other.value) == 0
 214                : isPresent == other.isPresent;
 215     }
 216 
 217     /**
 218      * Returns the hash code value of the present value, if any, or 0 (zero) if
 219      * no value is present.
 220      *
 221      * @return hash code value of the present value or 0 if no value is present
 222      */
 223     @Override
 224     public int hashCode() {
 225         return isPresent ? Double.hashCode(value) : 0;
 226     }
 227 
 228     /**
 229      * Returns a non-empty string representation of this OptionalDouble suitable for
 230      * debugging. The exact presentation format is unspecified and may vary
 231      * between implementations and versions.
 232      *
 233      * @implSpec If a value is present the result must include its string
 234      * representation in the result. Empty and present OptionalDoubless must be
 235      * unambiguously differentiable.
 236      *
 237      * @return the string representation of this instance
 238      */
 239     @Override
 240     public String toString() {
 241         return isPresent
 242                 ? String.format("OptionalDouble[%s]", value)
 243                 : "OptionalDouble.empty";
 244     }
 245 }