Skip to content

Commit

Permalink
Clarify switch expression usage (dart-lang#4887)
Browse files Browse the repository at this point in the history
Fixes dart-lang#4865 

---------

Co-authored-by: Anthony Sansone <[email protected]>
Co-authored-by: Parker Lougheed <[email protected]>
  • Loading branch information
3 people authored and rmacnak-google committed Sep 5, 2023
1 parent 4888543 commit badbbb0
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions src/language/branches.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,20 +129,23 @@ check out the patterns documentation on [Switch statements and expressions][].

### Switch expressions

A `switch` expression is similar to a `switch` statement, but you can use them
anywhere you can use an expression. They produce a value based on the expression
body of whichever case matches.
A `switch` _expression_ produces a value based on the expression
body of whichever case matches.
You can use a switch expression wherever Dart allows expressions,
_except_ at the start of an expression statement. For example:

The syntax of a `switch` expression differs from `switch` statement syntax:
```dart
var x = switch (y) { ... };
- Cases _do not_ start with the `case` keyword.
- A case body is a single expression instead of a series of statements.
- Each case must have a body; there is no implicit fallthrough for empty cases.
- Case patterns are separated from their bodies using `=>` instead of `:`.
- Cases are separated by `,` (and an optional trailing `,` is allowed).
- Default cases can _only_ use `_`, instead of allowing both `default` and `_`.
print(switch (x) { ... });
return switch (x) { ... };
```

Switch expressions allow you to rewrite a _statement_ like this:
If you want to use a switch at the start of an expression statement,
use a [switch statement](#switch-statements).

Switch expressions allow you to rewrite a switch _statement_ like this:

```dart
// Where slash, star, comma, semicolon, etc., are constant variables...
Expand Down Expand Up @@ -170,6 +173,15 @@ token = switch (charCode) {
};
```

The syntax of a `switch` expression differs from `switch` statement syntax:

- Cases _do not_ start with the `case` keyword.
- A case body is a single expression instead of a series of statements.
- Each case must have a body; there is no implicit fallthrough for empty cases.
- Case patterns are separated from their bodies using `=>` instead of `:`.
- Cases are separated by `,` (and an optional trailing `,` is allowed).
- Default cases can _only_ use `_`, instead of allowing both `default` and `_`.

{{site.alert.version-note}}
Switch expressions require a [language version][] of at least 3.0.
{{site.alert.end}}
Expand Down

0 comments on commit badbbb0

Please sign in to comment.