Re:Java 17 / JDK 17: General Availability
by bdamm on Tuesday September 14, 2021 @12:59PM
(#28527584)
This really sounds like the way to go, although of course it is too late for Java. Optional feels awkward, and there's no more safety than we already have since the JVM null-checks anyway.
if( arg.isPresent() ) ...
vs if( arg != null ) ...
How is this better?
Re:Java 17 / JDK 17: General Availability
by rovolo on Tuesday September 14, 2021 @02:24PM
(#28528683)
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.
Re:Java 17 / JDK 17: General Availability
by dtech on Wednesday September 15, 2021 @09:29AM
(#28538803)
Luckily it's not too late. A C#/Kotlin approach could be introduced and would not interfere with existing Optional.
The type system would need to be extended with a T? (nullable), T! (non-nullable), smart-casting on null-checks, and with some annotations or a flag to determine if T should be treated as T? or T! and whether you can call methods on it.
> How is this better?
It's not if you use Optional.get, but if you use .map, .orElse and the like the compiler can prevent you from getting NPEs instead of them being runtime.
So then you get the best of both world, the safety of Optional without the boxing overhead.
[1] https://kotlinlang.org/docs/null-safety.html