typestar

Enhanced enums in Dart

Dart enums are classes: fields, constructors, members.

// Dart enums are classes: fields, constructors, and members.
enum Tide {
  low(0.4),
  mid(1.1),
  high(2.3);

  final double meters;
  const Tide(this.meters);

  bool get wadersFeeding => this != Tide.high;
}

void main() {
  for (final tide in Tide.values) {
    print('${tide.name}: ${tide.meters} m, '
        'waders ${tide.wadersFeeding ? 'feeding' : 'roosting'}');
  }
}

How it works

  1. Each value calls the const constructor: low(0.4).
  2. final double meters rides along on every value.
  3. wadersFeeding is a getter computed per value; .name prints itself.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
351
Tokens
95
Three-star pace
65 tpm

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

Type this snippet

Step 3 of 3 in Classes, step 15 of 27 in Language basics.

← Previous Next →