I want to initialize a final variable in a class to this.
Class C{
final int variable1 = 0; //dynamically generated value
final int variable2;
C(): this.variable2 = this.variable1 + 1; //variable2 need access to "this" to initialize
}
You could use a private constructor with a public factory constructor.
class C {
final int variable1;
final int variable2;
C._(this.variable1, this.variable2);
factory C() {
var v1 = Random().nextInt(10);
return C._(v1, v1 + 1);
}
@override
String toString() => 'Instance of C $variable1 $variable2';
}
With regard to the API of your class, a final
member variable is not really any different from providing a getter. Since you want variable2
to never be reassigned and to be based on variable1
, it could exist solely as a getter:
class C {
final int variable1 = 0;
int get variable2 => variable1 + 1;
...
}
If you don't want to repeat the computation every time variable2
is accessed, you could use a private member variable with a public getter:
class C {
final int variable1 = 0;
int get variable2 => _variable2;
int _variable2;
C() {
_variable2 = variable1 + 1;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.