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.2

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.

The pub.dev package page can be found here.

Libraries

result_monad
A Dart implementation of the Result Monad which models success (ok) or failure (error) operation return types to allow for more expressive return generation/processing without using exceptions