You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Eric Milles (Jira)" <ji...@apache.org> on 2022/05/02 17:42:00 UTC

[jira] [Commented] (GROOVY-10616) Add peek extension method for Optional, OptionalInt, OptionalLong and OptionalDouble

    [ https://issues.apache.org/jira/browse/GROOVY-10616?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17530865#comment-17530865 ] 

Eric Milles commented on GROOVY-10616:
--------------------------------------

[~paulk] This is a non-essential proposed addition as there are several alternatives.  Do you think these extensions would be valuable enough?  There is an open proposal for supporting Optional -> Collection, which I mention because it also discusses several options for achieving the proposed behavior with the current Groovy/Java API.

> 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
>
> {{{}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.7#820007)