Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 810
Blackbam Avatar asked Oct 02 '22 01:10

Blackbam


People also ask

Can final be initialized in constructor?

A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.

How do you initialize an object in a constructor?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.

Can you set final variable in constructor?

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.


2 Answers

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));
}
like image 183
w.brian Avatar answered Oct 21 '22 13:10

w.brian


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);
  }
}
like image 92
rkj Avatar answered Oct 21 '22 13:10

rkj