< prev index next >

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

Print this page
rev 14279 : [mq]: 8140281-deprecation-optional.get

*** 108,129 **** --- 108,161 ---- /** * If a value is present, returns the value, otherwise throws * {@code NoSuchElementException}. * + * @deprecated + * This method's name {@code getAsDouble} makes it the obvious method to + * call to retrieve the value from this {@code OptionalDouble}. However, it has + * no mechanism to avoid an exception if this {@code OptionalDouble} is empty. + * This tends to lead to code that mishandles empty {@code OptionalDouble} + * values. Consider using other methods that handle the case where + * the {@code OptionalDouble} might be empty, such as + * {@link #ifPresent(java.util.function.DoubleConsumer) ifPresent()} + * and related methods, and + * {@link #orElse(double) orElse()} and related methods. + * Use {@link getWhenPresent()} when it is known that a value is + * always present. + * * @return the value described by this {@code OptionalDouble} * @throws NoSuchElementException if no value is present * @see OptionalDouble#isPresent() */ + @Deprecated(since="9") public double getAsDouble() { if (!isPresent) { throw new NoSuchElementException("No value present"); } return value; } /** + * If a value is present, returns the value, otherwise throws + * {@code NoSuchElementException}. + * + * @apiNote + * Use this method only when it is known that a value is always present. + * + * @return the value described by this {@code OptionalDouble} + * @throws NoSuchElementException if no value is present + * @see OptionalDouble#isPresent() + */ + public double getWhenPresent() { + if (!isPresent) { + throw new NoSuchElementException("No value present"); + } + return value; + } + + /** * If a value is present, returns {@code true}, otherwise {@code false}. * * @return {@code true} if a value is present, otherwise {@code false} */ public boolean isPresent() {
< prev index next >