Skip to content

Commit

Permalink
Fix sealed exhaustiveness example (#5470)
Browse files Browse the repository at this point in the history
This PR fixes `sealed` exhaustiveness code example:
https://dart.dev/language/class-modifiers-for-apis#the-sealed-modifer

---------

Co-authored-by: Parker Lougheed <[email protected]>
  • Loading branch information
ksokolovskyi and parlough authored Jan 17, 2024
1 parent ad95b5d commit dd9f3f4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
14 changes: 14 additions & 0 deletions examples/language/lib/class_modifiers/sealed_exhaustiveness.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// amigos.dart
sealed class Amigo {}

class Lucky extends Amigo {}

class Dusty extends Amigo {}

class Ned extends Amigo {}

String lastName(Amigo amigo) => switch (amigo) {
Lucky _ => 'Day',
Dusty _ => 'Bottoms',
Ned _ => 'Nederlander',
};
18 changes: 11 additions & 7 deletions src/language/class-modifiers-for-apis.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,8 @@ In return, you have the fewest restrictions as the class maintainer.
You can add new methods, turn constructors into factory constructors, etc.
without worrying about breaking any downstream users.

## The `sealed` modifer
<a id="the-sealed-modifer"></a>
## The `sealed` modifier

The last modifier, [`sealed`](/language/class-modifiers#sealed), is special.
It exists primarily to enable [exhaustiveness checking][] in pattern matching.
Expand All @@ -241,19 +242,22 @@ then the compiler knows the switch is exhaustive.

[exhaustiveness checking]: /language/branches#exhaustiveness-checking

<?code-excerpt "language/lib/class_modifiers/sealed_exhaustiveness.dart"?>
```dart
// amigos.dart
sealed class Amigo {}
class Lucky extends Amigo {}
class Dusty extends Amigo {}
class Ned extends Amigo {}
String lastName(Amigo amigo) =>
switch (amigo) {
case Lucky _ => 'Day';
case Dusty _ => 'Bottoms';
case Ned _ => 'Nederlander';
}
String lastName(Amigo amigo) => switch (amigo) {
Lucky _ => 'Day',
Dusty _ => 'Bottoms',
Ned _ => 'Nederlander',
};
```

This switch has a case for each of the subtypes of `Amigo`.
Expand Down

0 comments on commit dd9f3f4

Please sign in to comment.