3 ms·
This sounds really nice. Can you think of languages that implement it this way?
by rewgs 3y ago
This sounds really nice. Can you think of languages that implement it this way?
- spenczar5 3y agoRust does.
- tombert 3y agoI'm mostly familiar with it in F#, Scala, and Haskell, but I suspect any language with some functional roots has an equivalent. The F# For Fun and Profit blog has a decent post explaining it. That blog doesn't appear to be maintained anymore, but it is archived: https://web.archive.org/web/20180329001511/https://fsharpforfunandprofit.com/posts/recipe-part2/ https://web.archive.org/web/20180329001511/https://fsharpfor... You can find examples in Scala with `for` comprehensions as well.
- arrakeen 3y agojava: Optional<String> result = returnsAnOptional(); if (result.isPresent()) { log.info("result is {}", result.get()); } // and returnsAnOptional().map(r -> log.info("result is {}", r);
- tombert 3y 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 3y agomy post was mostly facetious, but it is as you say: possible but probably not something anyone would want to use
- tombert 3y 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 ;)
- rhinoceraptor 3y agoRust's error handling is in my opinion perfect. An operation that can fail will return a Result<T, E> type, it will either be Ok(T), or Err(E). You can pattern match a Result, and decide what to do with it. Or, more likely, you just want to pass that error back up to your calling function to decide what to do with it, so you just put a ? on the end of your function call like this: let result = potentially_failing_function()?;