问题描述
我有以下形式的作业&空检查以避免在我的地图中进行重复查找。
在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))
);
}
推荐答案
知道的运算符可用于这种情况:
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,如果 ??
运算符返回左侧,则运算符会短路至右侧;
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)
因此将得出空
,如果去向[a]
为空
,或者布尔结果为包含(b)
,如果不是。
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
和 outConn
均保证为非空,从而使我们可以返回 |||
两者。
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空值检查惯用语或最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!