Pattern matching for java.util.Optional
Swaranga Sarma
sarma.swaranga at gmail.com
Fri Jan 26 11:44:10 UTC 2024
>From what I have seen in some examples, I believe you will be able to do:
switch(opt) {
case Optional.of(var value) -> // use non-null value here
case Optional.empty() -> // handle absent case
}
This will likely be possible with the introduction of deconstruction
patterns:
https://gist.github.com/babanin/9ddf60279a9cbe50260ddb11d1aa2e80#recovering-static-factory-arguments
Regards
Swaranga
On Fri, Jan 26, 2024 at 12:35 AM Red IO <redio.development at gmail.com> wrote:
> Now that pattern matching is nearly complete I was thinking about the
> distinction how the option type of the jdk works.
> What I'm talking about is the split between checking if it's empty and
> retrieving the value.
> Sure there are ways to transform the optional and GetOrElse and Throw
> varients. But none of them express the connection between isPresent and get:
> var option = Optional.of("Foo");
> if (option.isPresent()) {
> var foo = option.get();
> }
> Now pattern matching comes into play. A great solution that is used by
> many other languages to deal with the option type is matching rather or not
> it's present and in the same step providing the value to the valid code
> block. Something like this:
> var option = Optional.of("Foo");
> switch(option) {
> case Some(foo) -> {}
> case None() -> {}
> }
> Or
> if(option instanceof Some(foo) {
>
> }
>
> This is indeed possible in the current version of java using sealed types,
> records and pattern matching.
> Now it's sad that Optional was introduced before the features we have now
> where available and introducing a second option type would be confusing and
> terrible for apis.
>
> But I don't think all hope is lost yet. I'm not too familiar with binary
> compatibility but from an api standpoint it would not change the public api
> of optional if it was turned from a final class into a sealed interface
> with 2 inner records representing the 2 states of the Optional instead of a
> nullable field. This way the public api of optional would just be added 2
> inner types and otherwise stay the same.
>
> I would love to hear your feedback on this one.
>
> Great regards
> RedIODev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240126/eb8a3c9b/attachment.htm>
More information about the amber-dev
mailing list