< prev index next >

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

Print this page
rev 48216 : 8140281: add no-arg Optional.orElseThrow() as preferred alternative to get()
Reviewed-by: XXX

*** 115,132 **** /** * If a value is present, returns the value, otherwise throws * {@code NoSuchElementException}. * * @apiNote ! * The methods {@link #orElse(int) orElse} and ! * {@link #orElseGet(IntSupplier) orElseGet} ! * are generally preferable to this method, as they return a substitute ! * value if the value is absent, instead of throwing an exception. * * @return the value described by this {@code OptionalInt} * @throws NoSuchElementException if no value is present - * @see OptionalInt#isPresent() */ public int getAsInt() { if (!isPresent) { throw new NoSuchElementException("No value present"); } --- 115,128 ---- /** * If a value is present, returns the value, otherwise throws * {@code NoSuchElementException}. * * @apiNote ! * The preferred alternative to this method is {@link #orElseThrow()}. * * @return the value described by this {@code OptionalInt} * @throws NoSuchElementException if no value is present */ public int getAsInt() { if (!isPresent) { throw new NoSuchElementException("No value present"); }
*** 223,232 **** --- 219,243 ---- public int orElseGet(IntSupplier supplier) { return isPresent ? value : supplier.getAsInt(); } /** + * If a value is present, returns the value, otherwise throws + * {@code NoSuchElementException}. + * + * @return the value described by this {@code OptionalInt} + * @throws NoSuchElementException if no value is present + * @since 10 + */ + public int orElseThrow() { + if (!isPresent) { + throw new NoSuchElementException("No value present"); + } + return value; + } + + /** * If a value is present, returns the value, otherwise throws an exception * produced by the exception supplying function. * * @apiNote * A method reference to the exception constructor with an empty argument
< prev index next >