typed_result 1.0.0
typed_result: ^1.0.0 copied to clipboard
A result monad with two subtypes representing a success or a failure
typed_result provide a convenience Result monad to represent success and error.
A Result<T, E> class can be either a success (Ok<T> class) or an error (Err<E> class).
// Result<T, E> --+-- Ok<T>
// |
// +-- Err<E>
Features #
This package aims to provide convenience methods for:
- Getting a value (
get,getOr,getOrThrow,getError,getErrorOrandgetErrorOrThrow) - Mapping a Result value into another Result (
map,mapErrorandmapBoth) - Execute a block based on the result (
onSuccessandonFailure), (when) - Wrap a block, transforming it's exception into error (
runCatching) - Wrap any value to a result based on the nullability (
toResultOr)
Usage #
An Result<T, E> can't be instantiated directly.
To create a Result, simply create an instance of Ok<T> or Err<E>.
var result = Ok(1); // as Ok<int>
var result = Err(""); // as Err<String>
Result<int, String> result = Ok(1); // as Result<int, *>, where * can be defined with any type
Result<int, String> result = Err(""); // as Result<*, String>, where * can be defined with any type
// As a return of a function
Result<int, String> getData() {
if(condition) {
return Ok(1);
} else {
return Err("");
}
}
Additional information #
This package is hugely based on a Kotlin library made by Michael Bull.
The motivation for creating this package comes from using this library in Kotlin projects and missing these features in Dart.