skyreach_result 1.0.0 skyreach_result: ^1.0.0 copied to clipboard
Provide a common and easy-to-use Result type
This package provides a Result type under which success (Ok) and failure (Err) are represented. The Result type is a type of Union(Either) that is specialized for error handling and has useful methods for error handling.
Usage #
Creating a Result object #
Result<int, String>.ok(42);
Result<int, String>.err("Error");
Ok or Err judgment #
final result = Result<int, String>.ok(42);
result.isOk; // true
result.isErr; // false
Getting the value of Result #
final result = Result<int, String>.ok(42);
// ok, err raises assertion error if value cannot be returned
result.ok; // 42
result.err; // AssertionError
// okOrNull, errOrNull returns null if no value can be returned
result.okOrNull; // 42
result.errOrNull; // null
// okOr, errOr returns the default value taken as argument if no value can be returned
result.okOr(100); // 42
result.errOr("hello"); // "hello"
Using and Converting Result Values #
final result = Result<int, String>.ok(42);
// If the Result type is ok, the first argument is executed, if the Result type is err, the second argument is executed
result.when(
(ok) => ok , // 42
(_) => expect(true, false), // not called
);
result.map<double>(
(ok) => ok.toDouble(),
(err) => 0.0
); // 42.0