英文:
What is the default value of dart non-nullable variables declared with late keyword?
问题
在空安全之前,我们知道如果我们像这样声明变量:
int a;
那么 a
指向一个空对象。
但是,现在有了声音空安全,当我们使用 late 关键字像这样声明 非空 变量时,
late int b;
那么,b
中的值是什么?或者换句话说,b
指向什么?
英文:
Before null-safety, we know that if we declare variable like this
int a;
Then a
is pointing to a null object.
But, now with sound null safety, when we declare the non-nullable variable with late keyword like this,
late int b;
Then, what is the value in b
? or in other words, b
is pointing to what ?
答案1
得分: 1
late
关键字表示你将尽快定义新值,但绝对会定义,所以如果你不设置任何值并使用它,它将引发异常,如下所示:
LateInitializationError: 字段 'b' 尚未初始化。
因此,这并不意味着在使用它时b
为null,而是意味着尽管现在它为null,但在你使用b
之前它将很快获得值。
英文:
The late
keyword means that you are going to define new value as soon as possible, but you definitely will, so if you won't set any value to and use it, it will through an exception like this:
LateInitializationError: Field 'b' has not been initialized.
So it does not mean that b
is null when you use it, it means that although it is null now it will get value very soon before you use b
.
答案2
得分: -1
late
关键字用于尽早初始化。因此,您需要检查数据是否为null。如果它为null,意味着您应该初始化或赋值。
late int N;
print(N ?? 123); // 检查 N 是否为null,如果为null,则默认赋值为123。
英文:
please check here
late
keyword is used initialise soon. so you need check that data is null or not. if it's null means you should initialise or assign
late int N;
print(N ?? 123); // checking N is null if it null means by default assign the 123.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论