dart non-nullable variables declared with late keyword 的默认值是 null。

huangapple go评论61阅读模式
英文:

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. 

huangapple
  • 本文由 发表于 2023年2月6日 03:43:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定