Result
A Result
object lets you return the status of a function (e.g. success/fail) in addition to its return value.
Example
Let’s say you have a function that makes a Net call to a weather API that gets the current outside temperature.
If the weather API server is down, you can’t just return 0, because that would indicate 0 degrees.
By returning a Result object, you make it easier for the caller to get the temperature when everything is okay, and handle the error if there is a problem.
BackgroundResult objects are an implementation of the Option Type pattern that has gained traction among modern languages. This is a good alternative to exception handling via
try/catch
or special return codes.Example Usage
$result = runProcess() // Get the result. Fatal error if it fails. $data = $result.get() // Get the result, or the default if it fails. $data = $result.get('my default') // Or check explicitly for failure if !$result.isOk() { $failCode = $result.getFailCode() } fun runProcess { $isOk = riskyOperation() if $isOk { return Result.ok($correctData) } else { // Fail result with a custom failCode return Result.fail('missingData') } }