什么是 Dart 空检查习语或最佳实践? [英] What is the Dart null checking idiom or best practice?
问题描述
我有以下形式的分配&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)
如果 因此要么评估为 will thus either evaluate to 这意味着生成的语句将是以下之一: That means the resulting statement will be one of the following:
同样适用于 The same applies to the 这篇关于什么是 Dart 空检查习语或最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!outgoing[a]
是 null
,或者 contains(b) 的布尔结果,
null
如果不是.null
if outgoing[a]
is null
, or the boolean result of contains(b)
if it is not.bool outConn = null ?? false; // false
bool outConn = false ?? false; // false
bool outConn = true ?? false; // true
inConn
布尔值,这意味着 inConn
和 outConn
都保证非空,允许我们返回||
两者的结果.inConn
boolean, which means both inConn
and outConn
are guaranteed to be non-null, allowing us to return the result of ||
ing the two.