andThen<U> method
Calls op
if the result is `Ok`
, otherwise returns the `Err`
value of self
.
This function can be used for control flow based on Result
values.
Example
Basic Usage:
import 'package:dartsult/dartsult.dart';
Result<int, int> sq(int x) {
return Result.ok(x * x);
}
Result<int, int> err(int x) {
return Result.error(x);
}
main() {
assert(Result.ok<int, int>(2).andThen(sq).andThen(sq) == Result.ok<int, int>(16));
assert(Result.ok<int, int>(2).andThen(sq).andThen(err) == Result.error<int, int>(4));
assert(Result.ok<int, int>(2).andThen(err).andThen(sq) == Result.error<int, int>(2));
assert(Result.error<int, int>(3).andThen(sq).andThen(sq) == Result.error<int, int>(3));
}
Implementation
Result<U, E> andThen<U>(Result<U, E> Function(T val) op) {
if (_ok.val != null) {
return op(_ok.val!);
}
return Result.error(_error.val!);
}