result_monad 1.0.1 result_monad: ^1.0.1 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.
Features #
- Result Monad with standard
ok
anderror
constructors - Methods/properties for directly querying if it is encapsulating a success or failure result and to get those values
getValueOrElse
andgetErrorOrElse
methods to return a default value if it is not the respective desired monadandThen
andandThenAsync
for chaining together operations with short-circuit capabilitymapValue
andmapError
methods for transforming typesmatch
method for performing different operations on a success or failure monadfold
method 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: ^1.0.1
In your source code add the following import:
import 'package:result_monad/result_monad.dart';
Usage #
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.