4

I encountered a problem when writing the constructor in dart. I have a class with two final variables, initialize them in the constructor, the following is wrong, because the final variable has no setter method:

class Person{
  final String name;
  final int age; 

  // Error
  Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

but this is correct, why

class Person{
  final String name;
  final int age; 

  // Correct
  Person(String name, int age): this.name = name, this.age = age;
}
Liu Silong
  • 4,902
  • 3
  • 19
  • 28

1 Answers1

6

When the constructor body is executed, final fields are already sealed.

The constructor initializer list is executed before the constructor initializers of the super classes.

The constructor bodies are executed afterwards. Constructor body allows arbitrary code to be executed like reading from fields. This is why at this point the initialization of final fields has to be completed already, otherwise it would be possible to read from a not yet initialized final field.

The constructor initializer list is the supported window where final fields can be initialized. It does not allow reading from this (explicit or implicit) and is therefore safe.

This is just a measure to ensure object initialization always happens in predictable manner.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567