Booleans
DO
DO use ??
to convert null
to a boolean value.
This rule applies when an expression can evaluate true
, false
, or null
, and you need to pass the result to something that doesn’t accept null
. A common case is the result of a null-aware method call being used as a condition:
if (optionalThing?.isEnabled) {
print("Have enabled thing.");
}
This code throws an exception if optionalThing
is null
. To fix this, you need to “convert” the null
value to either true
or false
. Although you could do this using ==
, we recommend using ??
:
// If you want null to be false:
optionalThing?.isEnabled ?? false;
// If you want null to be true:
optionalThing?.isEnabled ?? true;
// If you want null to be false:
optionalThing?.isEnabled == true;
// If you want null to be true:
optionalThing?.isEnabled != false;
Both operations produce the same result and do the right thing, but ??
is preferred for three main reasons:
-
The
??
operator clearly signals that the code has something to do with anull
value. -
The
== true
looks like a common new programmer mistake where the equality operator is redundant and can be removed. That’s true when the boolean expression on the left will not producenull
, but not when it can. -
The
?? false
and?? true
clearly show what value will be used when the expression isnull
. With== true
, you have to think through the boolean logic to realize that means that anull
gets converted to false.