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>
This package aims to provide convenience methods for:
- Getting a value (
get
,getOr
,getOrThrow
,getError
,getErrorOr
andgetErrorOrThrow
) - Mapping a Result value into another Result (
map
,mapError
andmapBoth
) - Execute a block based on the result (
onSuccess
andonFailure
), (when
) - Wrap a block, transforming it's exception into error (
runCatching
) - Wrap any value to a result based on the nullability (
toResultOr
) - Testing results with custom matchers
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("");
}
}
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.