JDK-8193280 : (opt) add no-arg orElseThrow() as preferred alternative to get()
  • Type: CSR
  • Component: core-libs
  • Sub-Component: java.util
  • Priority: P3
  • Status: Closed
  • Resolution: Approved
  • Fix Versions: 10
  • Submitted: 2017-12-09
  • Updated: 2018-04-05
  • Resolved: 2017-12-14
Related Reports
CSR :  
Description
Summary
-------

Add a no-arg orElseThrow() method to java.util.Optional, OptionalDouble, OptionalInt, and OptionalLong.

Problem
-------

Optional.get() is an "attractive nuisance" because the name "get" is quite an obvious name, and
it ought to be frequently used. It's more often misused then used properly, and it's an outlier because
unlike most other get() methods, it throws an exception if the Optional is empty. Since the point
of Optional is to facilitate **handling** of the empty case, calling get() is often the wrong thing to do.

Solution
--------

Introduce a new method orElseThrow() that is synonymous with get(): it retrieves the value if it's present,
or it throws NoSuchElementException if empty. Adjust wording of the get() specification to state that
orElseThrow() is preferred, but otherwise don't change semantics or behavior of get(). Corresponding
changes for OptionalDouble, OptionalInt, and OptionalLong.

Specification
-------------

See attached specdiff.


Comments
Updated webrev.2 and specdiff.2 attached, with wording changes as requested.
14-12-2017

The second sentence of the first paragraph of Optional states: " If a value is present, isPresent() returns true and get() returns the value." Given that get is being demoted as a preferred way of interacting with Optional, I think this sentence should be rephrased to not imply get() is the intended method to call. Voting to approve this request conditional on an informative edit being made to not position get() as preferred way of interacting with Optional and that revised diff/specdiff being included in an update to this CSR.
14-12-2017