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

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

    XMLWordPrintable

Details

    • CSR
    • Resolution: Approved
    • P3
    • 10
    • core-libs
    • None
    • minimal
    • These methods are being added to classes that are all final. There are no behavioral changes to existing methods.
    • 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. webrev.2.zip
          295 kB
        2. specdiff.2.zip
          1.81 MB
        3. specdiff.0.zip
          1.81 MB

        Issue Links

          Activity

            People

              smarks Stuart Marks
              smarks Stuart Marks
              Alan Bateman, Brian Burkhalter
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: