dart-lang / dart-lang/language
Modeling a "Result" type is possible, but difficult
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
Playground: https://dartpad.dev/cb41699ff72a41cb9412ef48f47cf824.
---
I've really enjoyed Dart's 3 [class modifiers](https://dart.dev/language/class-modifiers) and [pattern matching](https://dart.dev/language/patterns).
I'm trying to implement a `Result` type, similar to [Rust's `std::result`](https://doc.rust-lang.org/std/result/):
```dart
sealed class Result {
const Result();
const factory Result.value(T value) = ValueResult._;
const factory Result.error(E error) = ErrorResult._;
}
final class ValueResult extends Result {
final T value;
const ValueResult._(this.value);
}
final class ErrorResult extends Result {
final E error;
const ErrorResult._(this.error);
}
```
As you can see in my [playground](https://dartpad.dev/cb41699ff72a41cb9412ef48f47cf824), it works! It's just a bit more complicated than I'd expect for a sealed type with only two sub-types (I can see how the implementation as-is works for traditional enum-like types). Here are the individual test cases I wrote:
```dart
// Doesn't work, the "else" case doesn't promote willSucceed to ErrorResult, despite the fact that it must be?
if (willSucceed is ValueResult) {
print('value: ${willSucceed.value}');
} else {
print('error: ${willSucceed.error}');
}
```
```dart
// Similar to above.
if (willSucceed case ValueResult(value: final value)) {
print('value: $value');
} else {
print('error: ${willSucceed.error}');
}
```
```dart
// Works, but is the most typing.
switch (willSucceed) {
case final ValueResult result:
print('value: ${result.value}');
case final ErrorResult result:
print('error: ${result.error}');
}
```
```dart
// Works, and is probably what I'd use.
switch (willSucceed) {
case ValueResult(: final value):
print('value: $value');
case ErrorResult(: final error):
print('error: $error');
}
```
---
Maybe there is a better way to do this I don't know about or this can serve as inspiration for type inference improvements.
Thanks!
Contributor guide
Research direction
Start with the linked DartPad playground and reproduce the four Result examples, then read the linked documentation on class modifiers and patterns. The issue does not specify a desired language change or acceptance test, so “done” would require a settled proposal and corresponding language specification work.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100