Safe navigation operator
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,[1] Swift,[2] Ruby,[3] C#,[4] Kotlin,[5] 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).
Examples
Groovy
Safe navigation operator:[6]
def name = article?.author?.name
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.
NSString *name = article.author[0].name;
Swift
Optional chaining operator:[7]
let name = article?.author?.name
Optional subscript operator:
let author = articles?[0].author
Ruby
Ruby supports the &.
safe navigation operator since version 2.3.0:[8]
name = article&.author&.name
C#
In C# 6.0 and above, basic null-conditional operators ?.
and ?[]
:[9]
String name = articles?[0].author?.name
Kotlin
Safe call operator:[10]
val name = article?.author?.name
Perl 6
Safe method call:[11]
my $name = $article.?author.?name;
See also
References
- ↑ "6.1. Safe navigation operator". Retrieved 2016-01-28.
- ↑ "Optional Chaining". Retrieved 2016-01-28.
- ↑ "Ruby 2.3.0 Released". Retrieved 2016-01-28.
- ↑ "Null-conditional Operators (C# and Visual Basic)". Retrieved 2016-01-28.
- ↑ "Null Safety". Retrieved 2016-01-28.
- ↑ "6.1. Safe navigation operator". Retrieved 2016-01-28.
- ↑ "Optional Chaining". Retrieved 2016-01-28.
- ↑ "Ruby 2.3.0 Released". Retrieved 2016-01-28.
- ↑ "Null-conditional Operators (C# and Visual Basic)". Retrieved 2016-01-28.
- ↑ "Null Safety". Retrieved 2016-01-28.
- ↑ "Perl 6 Operators". Retrieved 2016-06-28.