Patterns in Dart
Destructure and test in one motion, with guards.
void main() {
final reading = ('gust', 31);
// Patterns destructure and test in one motion.
final (kind, value) = reading;
print('$kind at $value kts');
// switch patterns guard with when and bind what they match.
final note = switch (reading) {
('gust', final v) when v > 25 => 'secure the scope: $v kts',
('gust', final v) => 'breezy: $v kts',
(final k, _) => 'unhandled reading kind: $k',
};
print(note);
// if-case tries one pattern without a full switch.
if (reading case (_, > 30)) {
print('Log an equipment check');
}
}
How it works
final (kind, value) = readingunpacks a record.- switch arms bind with
final vand guard withwhen. if (reading case (_, > 30))tries one pattern inline.
Keywords and builtins used here
casefinalifswitchvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 529
- Tokens
- 128
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 128 seconds.
Step 2 of 3 in Records & patterns, step 20 of 27 in Language basics.