Home > front end >  Why are instance variables declared without initialization having no compilation errors?
Why are instance variables declared without initialization having no compilation errors?

Time:09-10

A variable in Dart is non-nullable by default. How the heck x and y could be declared in a class without initialization having no compilation errors?

class Point {
  double x, y;

  // The main constructor for this class.
  Point(this.x, this.y);

  // Delegates to the main constructor.
  Point.alongXAxis(double x) : this(x, 0);
}

CodePudding user response:

Because you've already initialized them in the constructor, so before they are used, they will always have their values.

If you remove the constructor, it will give you compile time error:

class Point {
  double x, y; // Error
}

CodePudding user response:

From the documentation:

If you enable null safety, then you must initialize the values of non-nullable variables before you use them:

int lineCount = 0;

You don’t have to initialize a local variable where it’s declared, but you do need to assign it a value before it’s used. For example, the following code is valid because Dart can detect that lineCount is non-null by the time it’s passed to print():

int lineCount;

if (weLikeToCount) {
  lineCount = countLines();
} else {
  lineCount = 0;
}

print(lineCount);
  •  Tags:  
  • dart
  • Related