In object-oriented programming, the safe navigation operator (also known as optional chaining operator, safe call operator, null-conditional operator) is a binary operator that returns its second argument but null if the first argument is null. It is used to avoid sequential explicit null checks and assignments and replace them with method/property chaining. In programming languages where the navigation operator (e.g. ".") leads to an error if applied to a null object, the safe navigation operator stops the evaluation of a method/field chain and returns null as the value of the chain expression. It is currently supported in languages such as Groovy,Swift,Ruby,C#,Kotlin,CoffeeScript and others. There is currently no common naming convention for this operator, but safe navigation operator is the most widely used term.
The main advantage of using this operator is that it solves problem commonly known as pyramid of doom. Instead of writing multiple nested if
s programmer can just use usual chaining, but put question mark symbols before dots (or other characters used for chaining).
Safe navigation operator:
Normal navigation syntax can be used in most cases without regarding NULLs, as the underlying messages, when sent to NULL, is discarded without any ill effects.
Optional chaining operator:
Optional subscript operator:
Ruby supports the &.
safe navigation operator (also known as the lonely operator) since version 2.3.0:
In C# 6.0 and above, basic null-conditional operators ?.
and ?[]
:
Safe call operator:
Safe method call: