result_monad 2.3.2
result_monad: ^2.3.2 copied to clipboard
A Dart implementation of the Result Monad which allows for more expressive result generation and processing without using exceptions.
A Dart implementation of the Result Monad found in Rust and other languages. This models either success (ok) or failure (error) of operations to allow for more expressive result generation and processing without using exceptions.
This blog post I wrote goes into the backgrounds of Result Monads and steps through the various aspects of the implementation for this library.
Features #
- Result Monad with standard
okanderrorconstructors - Methods/properties for directly querying if it is encapsulating a success or failure result and to get those values
runCatchingandrunCatchingAsyncto encapsulate thrown exception objects into error ResultsgetValueOrElseandgetErrorOrElsemethods to return a default value if it is not the respective desired monadandThen,transform,andThenAsync,transformAsyncfor chaining together operations with short-circuit capabilitywithResultandwithResultAsyncfor processing results in a pass-through capability with short-circuiting on thrown exceptionswithErrorandwithErrorAsyncfor processing errors in a pass-through capability with short-circuiting on thrown exceptionsmapValue,mapError,errorCastmethods for transforming success and failure typesmatchmethod for performing different operations on a success or failure monadfoldmethod for transforming the monad into a new result type with different logic for
Getting started #
In the pubspec.yaml of your Dart/Flutter project, add the following dependency:
dependencies:
result_monad: ^2.3.2
In your source code add the following import:
import 'package:result_monad/result_monad.dart';
Usage #
Below is a simple example but see the repository for feature rich versions:
import 'package:result_monad/result_monad.dart';
Result<double, String> invert(double value) {
if (value == 0) {
return Result.error('Cannot invert zero');
}
return Result.ok(1.0 / value);
}
void main() {
// Prints 'Inverse is: 0.5'
invert(2).match(
onSuccess: (value) => print("Inverse is: $value"),
onError: (error) => print(error));
// Prints 'Cannot invert zero'
invert(0).match(
onSuccess: (value) => print("Inverse is: $value"),
onError: (error) => print(error));
}
Additional information #
This result monad implementation takes inspiration from the Rust result type and the Kotlin Result implementation of the Result Monad.
The pub.flutter-io.cn package page can be found here.