什么是 Dart 空检查习语或最佳实践? [英] What is the Dart null checking idiom or best practice?

查看:29
本文介绍了什么是 Dart 空检查习语或最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式的分配&null 检查以避免在我的地图中进行双重查找.
在 Dart 中是否有更好或更惯用的方法来做到这一点?

I have the following form of assignment & null checks to avoid double lookups in my maps.
Is there a better or more idiomatic way to do this in Dart?

bool isConnected(a, b){
  List list;
  return (
    ((list = outgoing[a]) != null && list.contains(b)) ||
    ((list = incoming[a]) != null && list.contains(b))
  );
}

推荐答案

从 Dart 1.12 开始,空感知运算符可用于此类情况:

As of Dart 1.12 null-aware operators are available for this type of situation:

bool isConnected(a, b) {
  bool outConn = outgoing[a]?.contains(b) ?? false;
  bool inConn = incoming[a]?.contains(b) ?? false;
  return outConn || inConn;
}

?. 运算符在左侧为 null 时短路为 null,如果左侧为 null,?? 运算符返回左侧null,否则为右侧.

The ?. operator short-circuits to null if the left-hand side is null, and the ?? operator returns the left-hand side if it is not null, and the right-hand side otherwise.

声明

outgoing[a]?.contains(b)

如果 outgoing[a]null,或者 contains(b) 的布尔结果,

因此要么评估为 null 如果不是.

will thus either evaluate to null if outgoing[a] is null, or the boolean result of contains(b) if it is not.

这意味着生成的语句将是以下之一:

That means the resulting statement will be one of the following:

bool outConn = null ?? false; // false
bool outConn = false ?? false; // false
bool outConn = true ?? false; // true

同样适用于 inConn 布尔值,这意味着 inConnoutConn 都保证非空,允许我们返回|| 两者的结果.

The same applies to the inConn boolean, which means both inConn and outConn are guaranteed to be non-null, allowing us to return the result of ||ing the two.

这篇关于什么是 Dart 空检查习语或最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆