Pattern matching for java.util.Optional

Red IO redio.development at gmail.com
Fri Jan 26 07:30:01 UTC 2024


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/900bbc3a/attachment.htm>


More information about the amber-dev mailing list