[
https://issues.apache.org/jira/browse/GROOVY-10223?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17422438#comment-17422438
]
Paul King commented on GROOVY-10223:
------------------------------------
There is some existing functionality. Groovy truth is already catered for:
{code}
assert !Optional.empty()
assert Optional.of('something')
{code}
And there is an existing {{collect}} and a {{filter}} "by class" which retain
the {{Optional}} nature of the original {{Optional}}.
{code}
assert Optional.of("something").collect{ it.size() }.get() == 9
assert !Optional.empty().collect{ it.size() }.isPresent() // isPresent() is
optional since that is what Groovy truth would use anyway
assert !Optional.empty().filter(Number) // filter returns an optional
assert !Optional.of('x').filter(Number)
assert Optional.of(1234).filter(Number)
assert Optional.of(1234).filter(Number).get().equals(1234)
{code}
But you are correct that the complete list of possibilities isn't covered.
Perhaps a good way forward is to add more explicit {{Optional}} handling
variants as needed and also the {{asList()}} that you suggested which would
covered anyone wanting to jump out of the {{Optional}} nature.
> 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
> 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.3.4#803005)