In functional languages it is common to use pattern matching on optional types:
let result = match myOptional with
| Some x -> x * 2
| None -> 0
This is very helpful to the programmer, since the compiler checks that the pattern matches are complete.
However, in the examples for Java's Optional
that I have seen, isPresent
and get
are used instead:
Integer result;
if (myOptional.isPresent()) {
result = myOptional.get() * 2;
} else {
result = 0;
}
To me, this defeats the purpose of Optional
. The compiler does no checking to ensure that the both branches of the if
are implemented correctly, and the resulting code has no extra guarantees than the equivalent using null
.
This design choice discourages safety, so why does the standard library provide a get
function instead of just match
?