Safe navigation operator
In object-oriented programming, the Safe navigation operator (also known as Optional chaining operator, Safe call operator, Null-conditional operator) is an operator which is used to avoid sequental null checks and assignments and replace them with method/property chaining. While classic navigation operator throws null pointer exception if called on null object, safe navigation operator just stops evaluation of method/field chain and returns null as value of chain expression. It is currently supported in languages such as Groovy,[1] Swift,[2] Ruby,[3] C#,[4] Kotlin,[5] CoffeeScript and others. There's 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).
Contents
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
Ruby
Ruby supports different &.
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
See also
References
<templatestyles src="Reflist/styles.css" />
Cite error: Invalid <references>
tag; parameter "group" is allowed only.
<references />
, or <references group="..." />
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.