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

Note that Optional.orElse(T other) eagerly evaluates other

XMLWordPrintable

    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      I am writing this to enhance the documentation of orElse(T other) to incorporate the feedback about the eager evaluation of the other argument.

      T orElse(T other)

      Returns the value if present, otherwise returns other.

      Important Note: The other argument is evaluated eagerly. This means that if other is the result of a function invocation (e.g., orElse(myExpensiveFunction())), that function will be called and its result computed regardless of whether the Optional had a value present or not. If the Optional is present, the computed other value will simply be discarded.

      For situations where the default value is expensive to compute and should only be generated when truly needed (i.e., when the Optional is empty), consider using orElseGet(Supplier<? extends T> other) instead. The orElseGet method accepts a Supplier, which defers the computation of the default value until it's required.


            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated: