Last active
November 1, 2022 14:00
-
-
Save werediver/fc389c8e0467baf15ce584f4632e562b to your computer and use it in GitHub Desktop.
Container types and the `map()` function in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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