Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8193280

(opt) add no-arg orElseThrow() as preferred alternative to get()

    Details

    • Type: CSR
    • Status: Closed
    • Priority: P3
    • Resolution: Approved
    • Fix Version/s: 10
    • Component/s: core-libs
    • Labels:
      None
    • Subcomponent:
    • Compatibility Risk:
      minimal
    • Compatibility Risk Description:
      These methods are being added to classes that are all final. There are no behavioral changes to existing methods.
    • Interface Kind:
      Java API

      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.

        Attachments

        1. specdiff.0.zip
          1.81 MB
        2. specdiff.2.zip
          1.81 MB
        3. webrev.2.zip
          295 kB

          Issue Links

            Activity

              People

              • Assignee:
                smarks Stuart Marks
                Reporter:
                smarks Stuart Marks
                Reviewed By:
                Alan Bateman, Brian Burkhalter
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: