dart-lang / dart-lang/language

Allow switch without scrutinee and patterns in cases

Open
#3,457 15 comments 39 reactions 0 assignees View on GitHub
patterns request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Recently Dart 3 introduced switch expressions, although they facilitate type-casting-like flows through pattern matching, we still can't use flows where there is no compile-time pattern to match but a runtime expression to evaluate:

```dart
late final action;

if (isAvailableX()) {
action = doAndReturnX();
} else if (isAvailableY()) {
action = doAndReturnY();
} else if (isAvailableZ()) {
action = doAndReturnZ();
}
```

Using switch expression we are forced to give the switch the runtime object we want to work with along with the compile-time patterns:

```dart
final action = switch (null) {
_ when isAvailableX() => doAndReturnX(),
_ when isAvailableY() => doAndReturnY(),
_ when isAvailableZ() => doAndReturnZ(),
_ => null,
};
```

In Kotlin we can simply:

```kt
val action = when {
isAvailableX() -> doAndReturnX()
isAvailableY() -> doAndReturnY()
isAvailableZ() -> doAndReturnZ()
else -> null
}
```

A similar approach in Dart would be:

```dart
final action = switch {
isAvailableX() => doAndReturnX(),
isAvailableY() => doAndReturnY(),
isAvailableZ() => doAndReturnZ(),
_ => null,
};
```

Contributor guide

Open the contributing guide

Research direction

Start by reviewing the existing Dart switch-expression and pattern-matching design against the proposed scrutinee-free syntax. Compare the examples in this issue, including the fallback case and guarded conditions, and consider whether the proposed form preserves clear evaluation and exhaustiveness rules.

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
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.