[ 
https://issues.apache.org/jira/browse/GROOVY-10616?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
 ]

Paul King closed GROOVY-10616.
------------------------------

> Add peek extension method for Optional, OptionalInt, OptionalLong and 
> OptionalDouble
> ------------------------------------------------------------------------------------
>
>                 Key: GROOVY-10616
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10616
>             Project: Groovy
>          Issue Type: Improvement
>          Components: groovy-jdk
>            Reporter: Eric Milles
>            Assignee: Eric Milles
>            Priority: Minor
>             Fix For: 5.0.0-alpha-1
>
>
> {{{}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:
> {code:java}
> <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)
> {code}
> Example usage:
> {code:groovy}
> def test(Optional<?> opt) {
>   opt.peek { print it } // only prints if value present
>   opt.peek(it -> print it)
>   opt.peek(this::print)
> }
> {code}
> Alternatives/workarounds:
> {code:groovy}
> 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()
> }
> {code}



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to