typestar

Sealed classes in Dart

A closed hierarchy the compiler checks exhaustively.

// sealed closes the hierarchy: switches over it must be exhaustive.
sealed class HideEvent {}
class Arrival extends HideEvent {
  final String species;
  Arrival(this.species);
}

class Departure extends HideEvent {
  final int minutes;
  Departure(this.minutes);
}
String describe(HideEvent e) => switch (e) {
      Arrival(:final species) => '$species just landed',
      Departure(:final minutes) => 'gone after $minutes min',
    };

void main() {
  print(describe(Arrival('spoonbill')));
  print(describe(Departure(45)));
}

How it works

  1. sealed class HideEvent fixes the set of subtypes.
  2. Object patterns destructure fields: Arrival(:final species).
  3. No default arm needed — cover every case or it will not compile.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
501
Tokens
114
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 105 seconds.

Type this snippet

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

← Previous Next →