命名工厂构造方法不强制初始化final变量的疑问
来源:5-10 带你揭开Flutter中的面向对象(命名工厂构造方法)
MarcoLhc
2020-06-25
那final变量岂不是没有初始化,这个final修饰的变量岂不是只能用默认值了?
class Logger {
static Logger _instance;
final bool isOpen;
factory Logger() {
if (_instance == null) {
_instance = Logger._newInstance();
}
return _instance;
}
factory Logger.d() {
return Logger();
}
Logger._newInstance();///error here
void run(){
isOpen = true;///error here
}
}
写回答
1回答
-
CrazyCodeBoy
2020-06-28
Dart语法要求,final 变量必须在构造方法中进行初始化,并且不允许被修改,所以isOpen = true是不被允许的,上述代码可以这样来实现:
class Logger { static Logger _instance; final bool isOpen; factory Logger(isOpen) { if (_instance == null) { _instance = Logger._newInstance(isOpen); } return _instance; } factory Logger.d(isOpen) { return Logger(isOpen); } Logger._newInstance(this.isOpen);///error here void run(){ // isOpen = true;///error here } }
10
相似问题