5 ms·
The main advantage is that Optional is inconvenient and forces you to consider the null case. It's easy to forget that values can be null and assume they're not
by rovolo 5y ago
The main advantage is that Optional is inconvenient and forces you to consider the null case. It's easy to forget that values can be null and assume they're not, e.g. auto-unboxing
Long getSomeValue();
int max = Math.max(0, obj.getSomeValue());
The Optional value forces you to type some text basically acknowledging that the value can be null.
Optional<Long> getSomeValue();
... obj.getSomeValue().get());
I'm not saying Optional is a great solution. It's essentially a notification that a value is nullable.