class A {
A(int a);
}
class B extends A {
final int b;
B(int passed)
: b = passed * 10,
super(b); // Error
}
How can I pass b
value to the superclass constructor?
You cannot pass the field to the superclass constructor because the field doesn't exist until all constructor initializers have completed (because the object doesn't exist yet).
If you want to introduce a name for an intermediate value, so you can refer to it twice, you can use an intermediate constructor:
class B {
final int b;
B(int passed) : this._(passed * 10);
B._(this.b) : super(b);
}
This makes the B
constructor a forwarding generative constructor, which allows it to evaluate expressions and pass the results to another generative constructor. That's the only way to give a name to an intermediate value during constructor initialization.
Initialization lists do not have read access to instance variables.
In a simple example like the one you have listed, you can just use passed * 10
instead of b
For more involved computations though, you may want to move to a factory constructor
class A {
final int a;
A(this.a);
}
class B extends A {
final int b;
factory B(int passed){
var calculated;
// some complicated calculation
calculated= passed * 10;
return B._(passed, calculated);
}
B._(int passed, int calculated)
: b = passed,
super(calculated);
}
main() {
var b = B(2);
print (b.a);
}
You can optionally keep the class interface clean by making the default constructor private as I have here.