Safe navigation operator
In object-oriented programming, the safe navigation operator is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation as specified by the second argument.
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 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 was first used by Groovy 1.0 in 2007 and is currently supported in languages such as
C#, Swift, TypeScript, Ruby, Kotlin, Rust, JavaScript,
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 avoids the pyramid of doom. Instead of writing multiple nested
ifs, programmers can just use usual chaining, but add question mark symbols before dots.While the safe navigation operator and null coalescing operator are both null-aware operators, they are operationally different.
Examples
Apex
Safe navigation operator examples in Apex:a?.aMethod.aField // Evaluates to null if a null
a.aMethod?.aField // returns null if a.aMethod evaluates to null
String profileUrl = user.getProfileUrl?.toExternalForm;
return ?.Name;
C#
C# 6.0 and above have?., the null-conditional member access operator and ?, the null-conditional element access operator, which performs a null-safe call of an indexer get accessor. If the type of the result of the member access is a value type, the type of the result of a null-conditional access of that member is a nullable version of that value type.The following example retrieves the name of the author of the first article in an array of articles, and results in
null if the array is null, if its first element is null, if the Author member of that article is null, or if the Name member of that author is null. Note that an IndexOutOfRangeException is still thrown if the array is non-null but empty.string name = articles??.Author?.Name;
Calling a lambda requires
callback?.Invoke, as there is no null-conditional invocation.Func
int result = callback?.Invoke;
Clojure
doesn't have true operators in the sense other languages uses it, but as it interoperable with Java, and has to perform object navigation when it does, thesome-> macro can be used to perform safe navigation. An extended macro safe-> prevents calling nil values.CoffeeScript
Existential operator:Crystal
Crystal supports thetry safe navigation method Dart
Conditional member access operator:Gosu
Null safe invocation operator:The null-safe invocation operator is not needed for class attributes declared as Gosu Properties:
var foo: Foo = null
// the below will evaluate to null and not return a NullPointerException
var bar = foo.Bar
Groovy
Safe navigation operator and safe index operator:def name = article?.authors?.name
JavaScript
Added in ECMAScript 2020, the optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null. Major desktop browsers have supported this since 2020, and most mobile browsers added support by 2024.const name = article?.authors?.?.name
const result = callback?.
It short-circuits the whole chain of calls on its right-hand side: in the following example, bar is not "accessed".
null?.foo.bar
Kotlin
Safe call 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.Perl 5
does not have this kind of operator, but a proposal for inclusion was accepted with the following syntax:PHP
The null safe operator was accepted for PHP 8:Raku (Perl 6)
Safe method call:Ruby
Ruby supports the&. safe navigation operator since version 2.3.0:Rust
Rust provides a? operator that can seem like a safe navigation operator. However, a key difference is that when ? encounters a None value, it doesn't evaluate to None. Instead, it behaves like a return statement, causing the enclosing function or closure to immediately return None.The
Option methods map and and_then can be used for safe navigation, but this option is more verbose than a safe navigation operator:fn print_author
An implementation using
? will print nothing if article is None or article.unwrap.author is None. As soon as ? sees a None, the function returns.fn try_print_author -> Option<>
Scala
The null-safe operator in Scala is provided by the library Dsl.scala.The
@ ? annotation can be used to denote a nullable value.val root: Tree @ ? = Tree,
right = Tree
),
right = Tree
)
The normal
. in Scala is not null-safe, when performing a method on a null value.The exception can be avoided by using
? operator on the nullable value instead:The entire expression is
null if one of ? is performed on a null value.The boundary of a
null safe operator ? is the nearest enclosing expression whose type is annotated as @ ?.) should be
should be
Swift
Optional chaining operator, subscript operator, and call:let name = article?.authors?.name
let result = protocolVar?.optionalRequirement?
TypeScript
Optional chaining operator was included in the TypeScript 3.7 release:Visual Basic .NET
Visual Basic 14 and above have the?. and ?, similar to C#. They have the same behavior as the equivalent operators in C#.The following statement behaves identically to the C# example above.