Screening Results
How to reject success values and accept failure values
Screening mechanisms provide greater flexibility in handling edge cases and enable more robust error recovery strategies.
The following methods allow you to run inline tests on the wrapped value of a result to dynamically transform a success into a failure or a failure into a success.
Validating Success
The Result::filter
method allows you to transform a success into a failure based on certain conditions. It takes two parameters:
A
Predicate
to determine if the success value is acceptable.A mapping
Function
that will produce a failure value if the value is deemed unacceptable.
This can be used to enforce additional validation constraints on success values.
In this example, we use a lambda expression to validate that the success value inside result
is even. Since the number is odd, it transforms the result into a failure.
Note that it is illegal for the mapping function to return null
.
Recovering From Failure
The Result::recover
method allows you to transform a failure into a success based on certain conditions. It also receives two parameters:
A
Predicate
to determine if the failure value is recoverable.A mapping
Function
that will produce a success value from the acceptable failure value.
This method is useful for implementing fallback mechanisms or recovery strategies, ensuring the application logic remains resilient and adaptable.
In this example, we use method references to check if the failure value equals OK
and then transform the result into a success.
Conclusion
We covered how to filter out unwanted success values and accept failure values using filter
and recover
. These methods enable you to refine results based on specific criteria, ensuring that only the relevant values are processed down the line.
Last updated