Safe navigation operator

This is the current revision of this page, as edited by imported>Acuna007 at 14:40, 15 August 2024 (Added JavaScript to list of languages that support the operator). The present address (URL) is a permanent link to this version.

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

In object-oriented programming, the safe navigation operator (also known as optional chaining operator, safe call operator, null-conditional operator, null-propagation 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 (typically an object member access, array index, or lambda invocation).

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 was first used by Groovy 1.0 in 2007[1] and is currently supported in languages such as C#,[2] Swift,[3] TypeScript,[4] Ruby,[5] Kotlin,[6] Rust,[7] JavaScript,[8] 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 (or other characters used for chaining).

While the safe navigation operator and null coalescing operator are both null-aware operators, they are operationally different.

Examples

Apex

Safe navigation operator examples:[9]<syntaxhighlight lang="java"> a[x]?.aMethod().aField // Evaluates to null if a[x] == null a[x].aMethod()?.aField // returns null if a[x].aMethod() evaluates to null String profileUrl = user.getProfileUrl()?.toExternalForm(); return [SELECT Name FROM Account WHERE Id = :accId]?.Name; </syntaxhighlight>

C#

C# 6.0 and above have ?., the null-conditional member access operator (which is also called the Elvis operator by Microsoft and is not to be confused with the general usage of the term Elvis operator, whose equivalent in C# is ??, the null coalescing 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.[10]

The following example retrieves the name of the author of the first article in an array of articles (provided that each article has an Author member and that each author has an Name member), 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 (i.e. zero-length).

<syntaxhighlight lang="csharp">var name = articles?[0]?.Author?.Name;</syntaxhighlight>

Calling a lambda requires callback?.Invoke(), as there is no null-conditional invocation (callback?() is not allowed).

<syntaxhighlight lang="csharp">var result = callback?.Invoke(args);</syntaxhighlight>

Clojure

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, the some->[11] macro can be used to perform safe navigation.

<syntaxhighlight lang="clojure">(some-> article .author .name)</syntaxhighlight>

CoffeeScript

Existential operator:[12] <syntaxhighlight lang="coffeescript">zip = lottery.drawWinner?().address?.zipcode</syntaxhighlight>

Crystal

Crystal supports the try safe navigation method [13]

<syntaxhighlight lang="crystal">name = article.try &.author.try &.name</syntaxhighlight>

Dart

Conditional member access operator:[14]<syntaxhighlight lang="dart">var name = article?.author?.name</syntaxhighlight>

Gosu

Null safe invocation operator:[15]

<syntaxhighlight lang="gosu">var name = article?.author?.name</syntaxhighlight>

The null-safe invocation operator is not needed for class attributes declared as Gosu Properties:

<syntaxhighlight lang="gosu">class Foo {

   var _bar: String as Bar

}

var foo: Foo = null

// the below will evaluate to null and not return a NullPointerException var bar = foo.Bar</syntaxhighlight>

Groovy

Safe navigation operator and safe index operator:[1][16]

<syntaxhighlight lang="groovy"> def name = article?.authors?[0].name </syntaxhighlight>

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.[17] Major desktop browsers have supported this since 2020, and most mobile browsers added support by 2024.[18] <syntaxhighlight lang="javascript"> const name = article?.authors?.[0]?.name const result = callback?.() </syntaxhighlight>

It short-circuits the whole chain of calls on its right-hand side: in the following example, bar is not "accessed". <syntaxhighlight lang="javascript"> null?.foo.bar </syntaxhighlight>

Kotlin

Safe call operator:[6]

<syntaxhighlight lang="kotlin">val name = article?.author?.name</syntaxhighlight>

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. <syntaxhighlight lang="objc">NSString *name = article.author[0].name;</syntaxhighlight>

Perl 5

Perl 5 does not have this kind of operator, but a proposal for inclusion was accepted with the following syntax:[19] <syntaxhighlight lang="perl">my $name = $article?->author?->name;</syntaxhighlight>

PHP

The null safe operator was accepted for PHP 8:[20]

<syntaxhighlight lang="php">$name = $article?->author?->name;</syntaxhighlight>

Raku (Perl 6)

Safe method call:[21]

<syntaxhighlight lang="pl6">my $name = $article.?author.?name;</syntaxhighlight>

Ruby

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

<syntaxhighlight lang="ruby">name = article&.author&.name</syntaxhighlight>

Rust

Rust provides a ? operator[7] 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: <syntaxhighlight lang="rust"> fn print_author(article: Option<Article>) {

   println!(
       "Author: {}",
       article.and_then(|y| y.author)
           .map(|z| z.name)
           .unwrap_or("Unknown".to_owned())
   );

} </syntaxhighlight>

An implementation using ? will print nothing (not even "Author:") if article is None or article.unwrap().author is None. As soon as ? sees a None, the function returns. <syntaxhighlight lang="rust"> fn try_print_author(article: Option<Article>) -> Option<()>{

   println!("Author: {}", article?.author?.name);
   Some(())

} </syntaxhighlight>

Scala

The null-safe operator in Scala is provided by the library Dsl.scala.[22] [23]

<syntaxhighlight lang="scala">val name = article.?.author.?.name : @ ?</syntaxhighlight>

The @ ? annotation can be used to denote a nullable value.

<syntaxhighlight lang="scala">case class Tree(left: Tree @ ? = null, right: Tree @ ? = null, value: String @ ? = null)

val root: Tree @ ? = Tree(

 left = Tree(
   left = Tree(value = "left-left"),
   right = Tree(value = "left-right")
 ),
 right = Tree(value = "right")

)</syntaxhighlight>

The normal . in Scala is not null-safe, when performing a method on a null value.

<syntaxhighlight lang="scala">a[NullPointerException] should be thrownBy { root.right.left.right.value // root.right.left is null! }</syntaxhighlight>

The exception can be avoided by using ? operator on the nullable value instead:

<syntaxhighlight lang="scala">root.?.right.?.left.?.value should be(null)</syntaxhighlight>

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 @ ?.

<syntaxhighlight lang="scala">("Hello " + ("world " + root.?.right.?.left.?.value)) should be("Hello world null") ("Hello " + (("world " + root.?.right.?.left.?.value.?): @ ?)) should be("Hello null") (("Hello " + ("world " + root.?.right.?.left.?.value.?)): @ ?) should be(null)</syntaxhighlight>

Swift

Optional chaining operator,[3] subscript operator, and call:<syntaxhighlight lang=Swift> let name = article?.authors?[0].name let result = protocolVar?.optionalRequirement?() </syntaxhighlight>

TypeScript

Optional chaining operator was included in the Typescript 3.7 release:[4] <syntaxhighlight lang="typescript">let x = foo?.bar?.[0]?.baz();</syntaxhighlight>

Visual Basic .NET

Visual Basic 14 and above have the ?. (the null-conditional member access operator) and ?() (the null-conditional index operator), similar to C#. They have the same behavior as the equivalent operators in C#.[24]

The following statement behaves identically to the C# example above. <syntaxhighlight lang="vbnet">Dim name = articles?(0)?.Author?.Name</syntaxhighlight>

See also

References

  1. ^ 1.0 1.1 "Support the optional path operator (?.)". GitHub. Retrieved 2021-01-04.
  2. ^ "Null-conditional Operators (C# and Visual Basic)". Retrieved 2016-01-28.
  3. ^ 3.0 3.1 "Optional Chaining". Retrieved 2016-01-28.
  4. ^ 4.0 4.1 "Typescript 3.7". Retrieved 2019-11-06.
  5. ^ 5.0 5.1 "Ruby 2.3.0 Released". Retrieved 2016-01-28.
  6. ^ 6.0 6.1 "Null Safety". Retrieved 2016-01-28.
  7. ^ 7.0 7.1 "The question mark operator, ?". Retrieved 2021-10-04.
  8. ^ "MDN - optional chaining in JavaScript".
  9. ^ "Salesforce Winter 21 Release Notes". Salesforce. Retrieved 2020-10-13.
  10. ^ "Member access operators (C# reference)". Microsoft Docs. Microsoft. Retrieved 29 August 2019.
  11. ^ "Threading Macros Guide". Retrieved 2019-06-07.
  12. ^ "The Existential Operatior". Retrieved 2017-06-15.
  13. ^ "Crystal API: Object#try".
  14. ^ "Other Operators". A tour of the Dart language. Retrieved 2020-01-08.
  15. ^ "The Gosu Programming Language". Retrieved 2018-12-18.
  16. ^ "8.5. Safe index operator". Retrieved 2020-09-25.
  17. ^ "Optional Chaining in ECMAScript 2020".
  18. ^ "Browser Support for Optional Chaining in JavaScript".
  19. ^ "PPC 21 -- Optional Chaining". GitHub.
  20. ^ "PHP: rfc:nullsafe_operator". wiki.php.net. Retrieved 2020-10-01.
  21. ^ "Raku Operators". Retrieved 2022-09-16.
  22. ^ A framework to create embedded Domain-Specific Languages in Scala: ThoughtWorksInc/Dsl.scala, ThoughtWorks Inc., 2019-06-03, retrieved 2019-06-03
  23. ^ "NullSafe: Kotlin / Groovy flavored null-safe ? operator now in Scala". Scala Users. 2018-09-12. Retrieved 2019-06-03.
  24. ^ "?. and ?() null-conditional operators (Visual Basic)". Microsoft Docs. Microsoft. Retrieved 29 August 2019.

External links

  • PEP 505, discussing the possibility of safe navigation operators for Python