This feature radically simplifies a common programming pattern with the use of a single operator. Specifically, this pattern is the checking of nullable values prior to accessing or calling; however, this often results in tedious if statements:
// calling function on nullable variable
if(myObject != null) {
myObject.runMethod();
}
// accessing member in chain of possibly null values
final info = if(myObject != null && myObject.data != null && myObject.data.result != null) {
myObject.data.result.confirm();
} else {
null;
}
// alternatively...
final info = myObject != null ? (myObject.data != null ? (myObject.data.result != null ? myObject.data.result.confirm() : null) : null) : null;
The safe navigation operator drastically improves the size and readability of code in these situations. It turns what could be multiple lines or an over-extended line into a smaller expression.
// calling function on nullable variable
myObject?.runMethod();
// accessing member in chain of possibly null values
final info = myObject?.data?.result?.confirm();
This feature radically simplifies a common programming pattern with the use of a single operator. Specifically, this pattern is the checking of nullable values prior to accessing or calling; however, this often results in tedious
if
statements:The safe navigation operator drastically improves the size and readability of code in these situations. It turns what could be multiple lines or an over-extended line into a smaller expression.
Source: https://raw.githubusercontent.com/HaxeFoundation/haxe-evolution/master/proposals/0017-null-safe-navigation-operator.md