typestar

Named parameters in Dart

Braces make parameters named; required and defaults do the rest.

// Braces make parameters named; required marks the mandatory ones
// and = gives the rest defaults.
String logEntry(String species,
    {required int count, String hide = 'Reedbank', bool heard = false}) {
  final how = heard ? 'heard' : 'seen';
  return '$count $species $how from $hide';
}

// An arrow body is a single returned expression.
int perHour(int total, int hours) => total ~/ hours;

void main() {
  print(logEntry('snipe', count: 2));
  print(logEntry('bittern', count: 1, heard: true, hide: 'North Scrape'));
  print('${perHour(42, 6)} birds per hour');
}

How it works

  1. {required int count, String hide = 'Reedbank'} mixes both.
  2. Call sites name what they pass: count: 2, heard: true.
  3. => gives perHour a one-expression body; ~/ divides to int.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
557
Tokens
126
Three-star pace
70 tpm

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

Type this snippet

Step 1 of 3 in Functions, step 7 of 27 in Language basics.

← Previous Next →