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
extension Shout on Stringmakes'rare gull'.shout()legal.- Inside the body the receiver is
this, implicit or spelled. - Extensions add getters too:
207.bandCodepads withpadLeft.
Keywords and builtins used here
BandingShoutStringextensiongetintonvoid
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.
Step 3 of 3 in Functions, step 9 of 27 in Language basics.