StableValue vs Optional
Mickael Istria
mistria at redhat.com
Tue Jun 17 09:36:03 UTC 2025
Hi all,
(I'm new around here, so please excuse me for this late comment or in case
this was already discussed in some place I missed; I have seached Jira and
the mailing-list via search engine unsuccessfully).
I just discovered the StableValue proposal of JEP-502, that's a preview
feature for Java 25. I really welcome such change as -like most Java
developers- I've had to repeat some boilerplate code to create cached
values.
However, I have the impression that StableValue is a bit redundant with
Optional, and that maybe another approach based on Optional could work.
Concretely, I'm thinking of just adding some static constructor to Optional
that would be like `Optional<T> Optional.supplyNullable(Supplier<T>
supplier)`, one would be able to use it in such way:
```
Optional.supplyNullable(() -> {
String res;
...compute res...
return res;
})
```
and for more complex cases
```
Optional.supplyNullable(new Supplier<String>() {
private int state = 0;
@Override
String get() {
return stateful() + stateful() + stateless();
}
private String part1() {
return Integer.toString(state++);
}
private String part2() {
return System.getProperty("jvm.vendor");
}
})
```
and that would leave the ability to fully encapsulate/isolate the field
computation in the provided supplier (just like the StableValue) and that
would provide at least the immutability goal of StableValue. I'm not much
aware of the Optional internals to know whether it would fit other
requeirements (I actually didn't spot any other requirements on the JEP)
So I'm just sending that here so that this `Optional.supplyNullable(,,,)`
approach gets considered as an alternative. I honestly don't know whether
it'd be better, I just have a strong feeling that it can be worth having it
evaluated as an alternative in the JEP before things get final.
Cheers,
--
Mickael Istria
Eclipse IDE <https://www.eclipse.org/eclipseide> developer, for Red Hat
<https://developers.redhat.com/>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20250617/fffdfcd8/attachment.htm>
More information about the core-libs-dev
mailing list