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

Add consumer version of orElse to Optional and return Optional from ifPresent

XMLWordPrintable

      A DESCRIPTION OF THE REQUEST :
      At present, the implementation of ifPresent is:

          public void ifPresent(Consumer<? super T> consumer) {
              if (value != null)
                  consumer.accept(value);
          }

      I would like to request that the implementation be updated to:

          public Optional<T> ifPresent(Consumer<? super T> consumer) {
              if (value != null) {
                  consumer.accept(value);
              }
              return this;
          }

      and that an additional orElse method be added that takes a consumer as a parameter, i.e.:

          public void orElse(Consumer<? super T> consumer) {
              if (value == null) {
                  consumer.accept(value);
              }
          }

      This would allow the caller to make a clear concise set of method calls using a single line:

          Optional.ofNullable(value).ifPresent(this::doSomething).orElse(this::doSomethingElse);


      JUSTIFICATION :
      With the current implementation we can convert the following:

          if(value != null) {
              //Do something
              //...
          }

      to:

          Optional.ofNullable(value).ifPresent(this::doSomething);

      where the contents of the 'if' statement are moved into the method

          void doSomething(T value);

      We can also change the following:

          if(value == null) {
              throw new CustomException();
          }

      to:

          Optional.ofNullable(value).orElseThrow(CustomException::new);

      However, it would be nice to also be able to convert the following:

          if(value != null) {
              //Do something
          } else {
              throw new CustomException();
          }

      to:

          Optional.ofNullable(value).ifPresent(this::doSomething).orElseThrow(CustomException::new);

      Likewise, it would be really good if we could also convert:

          if(value != null) {
              //Do something
          } else {
              // Do something else
          }

      to:

          Optional.ofNullable(value).ifPresent(this::doSomething).orElse(this::doSomethingElse);


      In numerous places in our code base that could benefit from such an enhancement to Optional.


            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: