gberger
gberger

Reputation: 2863

Initializing final fields from a subclass in Dart

This does not work:

abstract class Par {
  final int x;
}

class Sub extends Par {
  Sub(theX) {
    this.x = theX;
  }
}

I get an error in Par saying x must be initialized:

warning: The final variable 'x' must be initialized
warning: 'x' cannot be used as a setter, it is final

Upvotes: 10

Views: 2338

Answers (1)

gberger
gberger

Reputation: 2863

Give the superclass a constructor, and make the subclass call super:

abstract class Par {
  final int x;
  Par (int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super(theX)
}

You can make the constructor private like so, because methods and fields starting with _ are private in Dart:

abstract class Par {
  final int x;
  Par._(int this.x) {}
}

class Sub extends Par {
  Sub(theX) : super._(theX)
}

Upvotes: 12

Related Questions