Is there a syntactic sugar to write the following code in a better way?
if (x != null && x.y != null) {
...things that use x!.y
}
I could write something like
if (x?.y != null) {
...things that use x!.y
}
but I don't think that is the same thing
CodePudding user response:
You should not use ! if you can instead write better code:
final item = x?.y;
if (item != null) {
// ...things that use item,
// a local variable elevated to non-null inside the scope of the if,
// no ! operator neccessary
}
CodePudding user response:
The x?.y != null is mostly equivalent to x != null && x.y != null except that it doesn't promote x to non-null.
To actually promote a variable, you need to test the variable directly.
I'd do:
if (x != null) {
var y = x.y;
if (y != null) {
// use y
}
}
in order to get promotion on both. Or do as @nvoght says and use x?.y to get the value into a variable, then promote that variable.
