4 ms·
I think the most benefit of wrapping the result in an optional is so you can use compiler to enforce exhaustive pattern matching[1]. Optional<Integer> num =
by andrewjf 10y ago
I think the most benefit of wrapping the result in an optional is so you can use compiler to enforce exhaustive pattern matching[1].
Optional<Integer> num = getSomeRiskyNumber();
match num {
Some(x) => ... ;
None => return error or whatever;
}
The compiler will verify you at least pretended to look at the None result instead of just ignoring it (but you could still swallow the none).
1: does java even have this?
- gravypod 10y agoTo my knowladge the Java library does not although it is fully capable of supporting this. I guess this is just an example of poor implementation. It could have been easily implemented like this Optional<X> x = ...; switch (status(x)) { case SOME: return x.get() * 10; case NONE: .... send error ... } Again I really like the matching functionality but as it stands, since it's not included, it's not worth much without it in my opinion. With match, that cleans up a LOT of code and if the compiler can guarantee no speed or memory hits for doing this it becomes very valuable very quick. It's one of the reasons I wanted to learn Rust.
- Sharlin 10y agoIncidentally, Scala discourages using pattern matching in cases like this (pun not intended), preferring the use of combinators (map/flatMap/etc).
- andrewaylett 10y agoThe closest equivalent would be something like: Optional<Integer> num = getSomeRiskyNumber(); return num.map(x -> ...).orElseGet(return error or whatever); Which is just as type-safe. There are a number of variants, including flatMap for when the map operation itself returns an Optional (the monadic bind operator) and a number of options for how to deal with the empty case.