Details
-
Improvement
-
Status: Closed
-
Minor
-
Resolution: Fixed
-
None
-
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
- is related to
-
GROOVY-10223 Add support for Optional to DefaultTypeTransformation.asCollection()
- Closed