dart_result aim to emulate the Result type from functional languages such as f# and rust.

There are some limitations on what is available using the Dart type system, but this library does (for certain use cases) serve it's purpose quite well.

Usage

A simple usage example:

import 'package:dart_result/dart_result.dart';

void main() {
  Result<int> truncDiv(int num1, int num2) {
    if (num2 == 0) {
      return Failure('cannot divide by zero');
    }
    return Success(num1 ~/ num2);
  }

  final successResult = truncDiv(5, 4);
  final failureResult = truncDiv(5, 0);

  final didSucceed = successResult.isSuccess;
  final didFail = failureResult.isFailure;
  final defaultVal = failureResult.getOrElse((failed) => 0);
  final matched =
      successResult.match((val) => val, (val) => 'Operation Failed');
  final mapped = successResult.mapSuccess((val) => val + 1);
  
  print('dividing 5 by 4 successful? : $didSucceed');
  // dividing 5 by 4 successful? : true
  
  print('dividing 5 by 0 failure? : $didFail');
  // dividing 5 by 0 failure? : true
  
  print('dividing 5 by 0 failed, default val provided: $defaultVal');
  // dividing 5 by 0 failed, default val provided: 0
  
  print('pattern match on $successResult returned: $matched');
  // match on Success{value: 1} returned: 1
  
  print('mapped $successResult to value of $mapped');
  // mapped Success{value: 1} to value of Success{value: 2}
}

Features and bugs

Please file feature requests and bugs at the tracker.

Libraries

dart_result
dart_result Is a library that exports the Result type. [...]