--- old/src/java.base/share/classes/java/util/OptionalLong.java 2016-04-25 14:50:40.000000000 -0700 +++ new/src/java.base/share/classes/java/util/OptionalLong.java 2016-04-25 14:50:39.000000000 -0700 @@ -107,13 +107,28 @@ } /** + * Equivalent to {@link #getWhenPresent()}. * If a value is present, returns the value, otherwise throws * {@code NoSuchElementException}. * + * @deprecated + * This method's name {@code getAsLong} makes it the obvious method to + * call to retrieve the value from this {@code OptionalLong}. However, it has + * no mechanism to avoid an exception if this {@code OptionalLong} is empty. + * This tends to lead to code that mishandles empty {@code OptionalLong} + * values. Consider using other methods that handle the case where + * the {@code OptionalLong} might be empty, such as + * {@link #ifPresent(java.util.function.LongConsumer) ifPresent()} + * and related methods, and + * {@link #orElse(long) orElse()} and related methods. + * Use {@link getWhenPresent()} when it is known that a value is + * always present. + * * @return the value described by this {@code OptionalLong} * @throws NoSuchElementException if no value is present * @see OptionalLong#isPresent() */ + @Deprecated(since="9") public long getAsLong() { if (!isPresent) { throw new NoSuchElementException("No value present"); @@ -122,6 +137,24 @@ } /** + * 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 OptionalLong} + * @throws NoSuchElementException if no value is present + * @see OptionalLong#isPresent() + */ + public long 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}