Creating Results
How to instantiate new Result objects
Last updated
Was this helpful?
How to instantiate new Result objects
Last updated
Was this helpful?
There are several ways to create result objects.
A successful result contains a non-null value produced by an operation when everything works as intended. We can use to create a new instance.
On the other hand, a failed result holds a value representing the problem that prevented the operation from completing. We can use to create a new one.
Failure values cannot be null
either.
This method enables compatibility with legacy or third-party code that uses exceptions to indicate operation failure.
We've covered how to create new instances of Result
using various factory methods provided by the Results
class. Each method serves a specific purpose, allowing you to select the most suitable one based on the situation.
When we need to create results that depend on a possibly null value, we can use . If the first argument is null
, then the second one will be used to create a failed result.
We can also use to create results that depend on an value. If the first argument is an empty optional, then the second one will be used to create a failed result.
The second argument can be a too.
Finally, if we have a task that may either return a success value or throw an exception, we can encapsulate it as a result using so we don't need to use a try-catch block.