typestar

var, final and const in Dart

Three ways to bind: mutable, once at run time, fixed at compile time.

void main() {
  // var infers and stays mutable; final binds once at run time;
  // const is fixed at compile time.
  var sightings = 12;
  sightings += 1;
  final opened = DateTime.now();
  const perch = 'north fence';

  // A type annotation replaces var when inference needs steering.
  double meanPerHour = sightings / 4;
  print('$sightings from the $perch since $opened');
  print('Rate: ${meanPerHour.toStringAsFixed(1)} per hour');
}

How it works

  1. var infers and stays assignable; += updates it.
  2. final binds once when the line runs — DateTime.now() is fine.
  3. const must be known at compile time; annotations replace var when needed.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
421
Tokens
72
Three-star pace
70 tpm

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

Type this snippet

Step 2 of 3 in Values, step 2 of 27 in Language basics.

← Previous Next →