Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-10616

Add peek extension method for Optional, OptionalInt, OptionalLong and OptionalDouble

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • None
    • 5.0.0-alpha-1
    • groovy-jdk
    • None

    Description

      java.util.Optional, et al. do not offer a direct method for consuming the value if present but returning the optional unchanged. A "peek" method similar to Stream#peek(Consumer<? super T>) would allow this without having to resort to using filter and always returning true or map and always returning the value or tap and isPresent in tandem or ".stream().peek(...).findFirst()".

      I considered "tap" but decided to leave existing tap semantics unchanged in case it is used with optionals.

      Proposed extension methods:

      <T> Optional<T> peek(Optional<T> self, Consumer<? super T> action)
          OptionalInt peek(OptionalInt self, IntConsumer action)
          OptionalLong peek(OptionalLong self, LongConsumer action)
          OptionalDouble peek(OptionalDouble self, DoubleConsumer action)
      

      Example usage:

      def test(Optional<?> opt) {
        opt.peek { print it } // only prints if value present
        opt.peek(it -> print it)
        opt.peek(this::print)
      }
      

      Alternatives/workarounds:

      def test(Optional<?> opt) {
        opt.filter { print it; true }
        opt.map { print it; return it }
        opt.tap { ifPresent(this::print) }
        opt.stream().peek(this::print).findFirst()
      }
      

      Attachments

        Issue Links

          Activity

            People

              emilles Eric Milles
              emilles Eric Milles
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: