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

Eric Milles commented on GROOVY-10223:
--------------------------------------

Here is my "iterator()" implementation, in case someone wants to try this out 
as a category method or whatever.  I do not see enough value to pursue it plus 
{{OptionalInt}}, {{OptionalLong}} and {{OptionalDouble}} variants.
{code:java}
    /**
     * If a value is present in the {@code Optional}, returns a single-element
     * {@code Iterator}; otherwise returns an empty {@code Iterator}.
     *
     * <pre class="groovyTestCase">
     * def iter = Optional.empty().iterator()
     * assert !iter.hasNext()
     *
     * iter = Optional.of('x').iterator()
     * assert iter.hasNext()
     * assert iter.next() == 'x'
     * assert !iter.hasNext()
     *
     * // for-each supported via iterator()
     * int values = 0
     * for (value in Optional.empty()) {
     *     values += 1
     * }
     * assert values == 0
     * for (value in Optional.of('x')) {
     *     assert value == 'x'
     *     values += 1
     * }
     * assert values == 1
     * </pre>
     */
    public static <T> Iterator<T> iterator(final Optional<T> self) {
        return 
self.map(Collections::singleton).orElseGet(Collections::emptySet).iterator();
    }
{code}

> Add support for Optional to DefaultTypeTransformation.asCollection()
> --------------------------------------------------------------------
>
>                 Key: GROOVY-10223
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10223
>             Project: Groovy
>          Issue Type: New Feature
>          Components: groovy-jdk
>            Reporter: Stephen Smith
>            Assignee: Eric Milles
>            Priority: Trivial
>              Labels: features
>
> The JDK recently added support for *Optional::stream()* which returns a 
> stream containing either the unwrapped value or an empty stream if the 
> *Optional* is empty.
> In the groovy-jdk, using iteration however will call
> {noformat}
> DefaultTypeTransformation.asCollection(){noformat}
> which does not specifically check for type *Optional*, instead it will just 
> wrap the *Optional* itself in a *List* rather than the unwrapped value as the 
> default behavior.
> Adding an _if else_ clause will allow using the Optional as either a single 
> or empty list.
> {code:java}
> if (value instanceOf Optional) {
>    return ((Optional)value).map(List::of).orElse(List.of())
> }{code}
>  Alternatively, add an *asList()* to the Optional class.
>  (edit: 2021-09-13, missing bracket in code example)
>  



--
This message was sent by Atlassian Jira
(v8.20.7#820007)

Reply via email to