dart-lang / dart-lang/language
`switch` should be considered exhaustive when an object of type S with a type parameter T shares T with one of its fields with type U, which is a sealed class, and has T checked against all possible types for U
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
Consider the following classes:
```dart
final class MyClass {
MyClass(this.s) : value = s.value;
final S s;
final T value;
}
sealed class S {
T get value;
}
final class SInt implements S {
int get value => 10;
}
final class SString implements S {
String get value => 'value';
}
final class SBool implements S {
bool get value => true;
}
```
Now, in the main file, the `switch` should be considered exhaustive:
```dart
void main() {
final myClass = getMyClass();
final string = switch (myClass) {
MyClass() => 'int: ${myClass.value.isOdd}',
MyClass() => 'string ${myClass.value.isEmpty}',
MyClass() => 'bool ${myClass.value ^ false}',
};
print(string);
}
MyClass getMyClass() => ...; // May return any kind of `MyClass`, so we declare T as Object?
```
This code emits an error saying that the `switch` did not check for `MyClass`.
As far as I can tell, considering that `S` is sealed and all its subtypes are final, there's no possible case where `T` would be anything other than `int`, `String`, `bool` or a subtype of one of them (`Never`?).
Thus, it should be safe for the `switch` to consider this as sound.
Related to: #3683
Contributor guide
Research direction
Start with the generic class and sealed-class example in the issue and reproduce the exhaustiveness error in the main file. Read related issue #3683 for surrounding context. Done means the shown switch is correctly recognized as exhaustive, with the language behavior and any required specification coverage established.
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
- Mostly clear
- Newbie friendliness
- 35/100