result_monad 1.0.0 copy "result_monad: ^1.0.0" to clipboard
result_monad: ^1.0.0 copied to clipboard

outdated

A Dart implementation of the Result Monad

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 and error constructors
  • Methods/properties for directly querying if it is encapsulating a success or failure result and to get those values
  • getValueOrElse and getErrorOrElse methods to return a default value if it is not the respective desired monad
  • andThen and andThenAsync for chaining together operations with short-circuit capability
  • mapValue and mapError methods for transforming types
  • match method for performing different operations on a success or failure monad
  • fold 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.0

In your source code add the following import:

import 'package:result_monad/result_monad.dart';

Usage #

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.