How do I initialize a final class property in a constructor?

Blackbam picture Blackbam · Mar 17, 2017 · Viewed 29.8k times · Source

In Java you are allowed to do this:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

In Dart, I tried:

class A {    
    final int x;

    A() {
        this.x = 5;
    }
}

I get two compilation errors:

The final variable 'x' must be initialized.

and

'x' can't be used as a setter because its final.

Is there a way to set final properties in the constructor in Dart?

Answer

w.brian picture w.brian · Mar 17, 2017

You cannot instantiate final fields in the constructor body. There is a special syntax for that:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  // Old syntax
  // Point(x, y) :
  //   x = x,
  //   y = y,
  //   distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));

  // New syntax
  Point(this.x, this.y) :
    distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}