typestar

Extension methods in Dart

Add members to types you do not own.

// An extension adds members to a type you do not own.
extension Shout on String {
  String shout() => '${toUpperCase()}!';
}

extension Banding on int {
  // this is the receiver inside an extension body.
  String get bandCode => 'RB-${toString().padLeft(4, '0')}';
}

void main() {
  print('rare gull'.shout());
  print(207.bandCode);
  print(7.bandCode);
}

How it works

  1. extension Shout on String makes 'rare gull'.shout() legal.
  2. Inside the body the receiver is this, implicit or spelled.
  3. Extensions add getters too: 207.bandCode pads with padLeft.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
347
Tokens
81
Three-star pace
70 tpm

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

Type this snippet

Step 3 of 3 in Functions, step 9 of 27 in Language basics.

← Previous Next →

Extension methods in other languages