typestar

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

  1. final (kind, value) = reading unpacks a record.
  2. switch arms bind with final v and guard with when.
  3. if (reading case (_, > 30)) tries one pattern inline.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Records & patterns, step 20 of 27 in Language basics.

← Previous Next →

Patterns in other languages