Conditional Actions
How to handle success and failure scenarios
We'll now delve into a set of methods that allow you to take conditional actions based on the state of a result. They provide a cleaner and more expressive way to handle success and failure scenarios, eliminating the need for lengthy if/else blocks.
Handling Success
We can use Result::ifSuccess
to specify an action that must be executed if the result represents a successful outcome. This method takes a consumer function that will be applied to the success value wrapped by the result.
In this example, ifSuccess
ensures that the provided action (adding the success value to the list) is only executed if the parsing operation is successful.
Handling Failure
On the other hand, we can use Result::ifFailure
method to define an action that must be taken when the result represents a failure. This method also takes a Consumer
that will be applied to the failure value inside the result.
Here, ifFailure
ensures that the provided action (adding the failure value to the list) is only executed if the parsing operation fails.
Handling Both Scenarios
Finally, Result::ifSuccessOrElse
allows you to specify two separate actions: one for when the operation succeeded and another for when it failed. This method takes two consumer functions: the first for handling the success case and the second for handling the failure case.
In this example, ifSuccessOrElse
simplifies conditional logic by providing a single method to handle both success and failure scenarios, making the code more concise and readable.
Conclusion
We explained how to handle success and failure scenarios using these three methods. They provide a powerful way to perform conditional actions based on the state of a Result, streamlining your error handling and making your code more readable and maintainable.
Last updated