4 ms·
java: Optional<String> result = returnsAnOptional(); if (result.isPresent()) { log.info("result is {}", result.get()); } // and r
by arrakeen 2y ago
java:
Optional<String> result = returnsAnOptional();
if (result.isPresent()) {
log.info("result is {}", result.get());
}
// and
returnsAnOptional().map(r -> log.info("result is {}", r);
- tombert 2y agoOptionals are a bit different though, since they don't provide a way to explicitly handle errors, just wrap the `null` value if it exists and force you to be more explicit about it. I don't know that there's a clean way to do the Either monad in Java without algebraic data types. You could certainly make a wrapper class that maybe has an optional `Left` and `Right` private variable and then make a `map` that handles the unboxing of those, but I think that might be a bit messy.
- arrakeen 2y agomy post was mostly facetious, but it is as you say: possible but probably not something anyone would want to use
- tombert 2y agoActually, I almost want to give it a try now. There's some messy try-catch Java code at work that might benefit. Don't worry, I won't deploy it until my team has seen it ;)