简体   繁体   中英

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

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?

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));
}

You can make it even shorter with this. syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors ):

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

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

If you have some more complicated initialization you should use factory constructor, and the code become:

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

  Point._(this.x, this.y, this.distanceFromOrigin);

  factory Point(num x, num y) {
    num distance = distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
    return new Point._(x, y, distance);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM