【问题标题】:Understanding difference between int? and int (or num? and num) [duplicate]了解int之间的区别?和int(或num?和num)[重复]
【发布时间】:2021-08-02 03:41:44
【问题描述】:

定义地图后(以字母为键,拼字游戏得分为值)

Map<String, int> letterScore //I'm omitting the rest of the declaration

当我尝试这个功能时(在 DartPad 中)

int score(String aWord) {
  int result = 0;
  for (int i = 0; i < aWord.length; ++i) {
    result += letterScore[aWord[i]];
  }

  return result;
}

无论我是通过将变量声明为num 还是int 来进行实验,我都会收到错误消息:

错误:“int?”类型的值不能分配给类型的变量 'num' 因为'int?'可以为空,并且'num'不是[我在将所有数值变量声明为int后得到了这个]

错误:不能从函数返回“num”类型的值 返回类型“int”。

错误:'num?' 类型的值不能分配给类型的变量 'num' 因为'num?'可以为空,而 'num' 不是。

我了解整数和浮点(或双精度)数之间的区别,它是 intint?numnum? 我不明白,以及使用哪种形式声明变量时。我应该如何声明和使用intnum 变量以避免这些错误?

【问题讨论】:

  • 您的问题是Map 上的[] 运算符返回一个可以是null 的值。原因是如果您在Map 中请求不存在的内容,它将返回null。因此,在您的情况下,letterScore 在使用 [] 运算符时将返回 int?
  • 因此,您需要处理[] 返回null 的情况。或者您可以使用letterScore[aWord[i]]!(参见! 符号)这将强制分析器停止抱怨,并且应该只看到该值不可为空。但是,如果[] 返回null,您将获得运行时异常。

标签: dart


【解决方案1】:

以此为例:

int x; // x has value as null
int x = 0; // x is initialized as zero

上面的代码都是很好的可编译代码。但是如果你启用了 Dart 的 null-safety 功能,你应该这样做,它会使上面的代码以不同的方式工作。

int x; // compilation error: "The non-nullable variable must be assigned before can be used"
int x = 0; // No Error.

这是编译器所做的努力,旨在警告您变量可能为空的任何位置,但在编译期间。太棒了。

但是,如果您必须将变量声明为 null,因为您在编译时不知道该值,会发生什么情况。

int? x; // Compiles fine because it's a nullable variable

? 是您告诉编译器您希望此变量允许null 的一种方式。但是,当你说一个变量可以是null,那么每次你使用这个变量时,编译器都会提醒你检查变量是否为空,然后才能使用它。

因此?的其他用途:

int? x;
print(x?.toString() ?? "0");

进一步阅读:

官方文档:https://dart.dev/null-safety/understanding-null-safety

Null 感知运算符:https://dart.dev/codelabs/dart-cheatsheet

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2014-01-02
    • 2012-12-08
    • 2013-07-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多