Skip to content

Instantly share code, notes, and snippets.

@werediver
Last active November 1, 2022 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save werediver/fc389c8e0467baf15ce584f4632e562b to your computer and use it in GitHub Desktop.
Save werediver/fc389c8e0467baf15ce584f4632e562b to your computer and use it in GitHub Desktop.
Container types and the `map()` function in Dart
void main() {
print(f(true).map((value) => value + 1));
print(f(false).map((value) => value + 1));
print([1, 2, 3].map((value) => "x ${value + 1}"));
print([].map((value) => value + 1));
}
// Methods like
// map, flatMap / expand, filter / where, firstWhere, reduce, fold
// are typically defined on "containers" like collections (array, set, etc.),
// `Optional<T>`, `Result<T, E>`, `Either<T, U>`.
class Result<Value, Error> {
Result.success(Value value): this.value = value, this.error = null;
Result.failure(this.error): this.value = null;
Result<T, Error> map<T>(T Function(Value) f) {
if (value != null) {
return Result.success(f(value!));
} else {
return Result.failure(error);
}
}
String toString() => "Result(value: $value, error: $error)";
final Value? value;
final Error? error;
}
Result<int, FError> f(bool allGood) {
if (allGood) {
return Result.success(42);
} else {
return Result.failure(FError.unknown);
}
}
enum FError { unknown }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment