Jump to content

Safe navigation operator

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Sashahhh (talk | contribs) at 16:36, 28 January 2016 (Created page with 'In computer programming, the '''Safe navigation operator''' '''<code>?.</code>''' (also known as '''Optional chaining operator''', '''Safe call operator''',...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In computer 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. It is currently supported in languages such as Groovy[1], Swift[2], Ruby [3], C#[4], Kotlin[5] and others. There's currently no common naming convention for this operator.

The main advantage of using this operator is that it solves 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).

Examples

Groovy

Null-safe operator:

def name = article?.author?.name

Swift

Optional chaining operator:

let name = article?.author?.name

Ruby

Ruby supports different &. safe navigation operator since version 2.3.0:

name = article$.author&.name

C#

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

String? name = articles?[0].author?.name

Kotlin

Safe call operator:

val name = article?.author?.name
  1. ^ "6.1. Safe navigation operator". Retrieved 2016-01-28.
  2. ^ "Optional Chaining". Retrieved 2016-01-28.
  3. ^ "Ruby 2.3.0 Released". Retrieved 2016-01-28.
  4. ^ "Null-conditional Operators (C# and Visual Basic)". Retrieved 2016-01-28.
  5. ^ "Null Safety". Retrieved 2016-01-28.