Kalpana Kalpana (Editor)

Safe navigation operator

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

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.

Contents

The main advantage of using this operator is that it solves a problem commonly known as pyramid of doom. Instead of writing multiple nested ifs programmer can just use usual chaining, but put question mark symbols before dots (or other characters used for chaining).

Groovy

Safe navigation operator:

Objective-C

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.

Swift

Optional chaining operator:

Optional subscript operator:

Ruby

Ruby supports the &. safe navigation operator (also known as the lonely operator) since version 2.3.0:

C#

In C# 6.0 and above, basic null-conditional operators ?. and ?[]:

Kotlin

Safe call operator:

Perl 6

Safe method call:

References

Safe navigation operator Wikipedia


Similar Topics