Share to: share facebook share twitter share wa share telegram print page

Safe navigation operator

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]

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;

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).

var name = articles?[0]?.Author?.Name;

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

var result = callback?.Invoke(args);

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.

(some-> article .author .name)

CoffeeScript

Existential operator:[12]

zip = lottery.drawWinner?().address?.zipcode

Crystal

Crystal supports the try safe navigation method [13]

name = article.try &.author.try &.name

Dart

Conditional member access operator:[14]

var name = article?.author?.name

Gosu

Null safe invocation operator:[15]

var name = article?.author?.name

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

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

Groovy

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

def name = article?.authors?[0].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.[17] Major desktop browsers have supported this since 2020, and most mobile browsers added support by 2024.[18]

const name = article?.authors?.[0]?.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:[6]

val 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;

Perl 5

Perl 5 does not have this kind of operator, but a proposal for inclusion was accepted with the following syntax:[19]

my $name = $article?->author?->name;

PHP

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

$name = $article?->author?->name;

Raku (Perl 6)

Safe method call:[21]

my $name = $article.?author.?name;

Ruby

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

name = article&.author&.name

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:

fn print_author(article: Option<Article>) {
    println!(
        "Author: {}",
        article.and_then(|y| y.author)
            .map(|z| z.name)
            .unwrap_or("Unknown".to_owned())
    );
}

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.

fn try_print_author(article: Option<Article>) -> Option<()>{
    println!("Author: {}", article?.author?.name);
    Some(())
}

Scala

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

val name = article.?.author.?.name : @ ?

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

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")
)

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

a[NullPointerException] should be thrownBy {
root.right.left.right.value // root.right.left is null!
}

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

root.?.right.?.left.?.value should be(null)

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

("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)

Swift

Optional chaining operator,[3] subscript operator, and call:

let name = article?.authors?[0].name
let result = protocolVar?.optionalRequirement?()

TypeScript

Optional chaining operator was included in the Typescript 3.7 release:[4]

let x = foo?.bar?.[0]?.baz();

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.

Dim name = articles?(0)?.Author?.Name

See also

References

  1. ^ a b "Support the optional path operator (?.)". GitHub. Retrieved 2021-01-04.
  2. ^ "Null-conditional Operators (C# and Visual Basic)". Retrieved 2016-01-28.
  3. ^ a b "Optional Chaining". Retrieved 2016-01-28.
  4. ^ a b "Typescript 3.7". Retrieved 2019-11-06.
  5. ^ a b "Ruby 2.3.0 Released". Retrieved 2016-01-28.
  6. ^ a b "Null Safety". Retrieved 2016-01-28.
  7. ^ a b "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.
  • PEP 505, discussing the possibility of safe navigation operators for Python

Read other articles:

Steven SpielbergLahirSteven Allan SpielbergPekerjaanSutradaraProduserPenulis skenarioTahun aktif1964–sekarangSuami/istriAmy Irving (1985-1989) Kate Capshaw (1991-sekarang) Steven Allan Spielberg (lahir 18 Desember 1946) adalah seorang sutradara dan produser film ternama asal Amerika Serikat. Ia telah memperoleh tiga Penghargaan Oscar (Academy Award) serta satu Penghargaan Kehormatan Seumur Hidup. Kehidupan awal dan latar belakang Steven Allan Spielberg lahir pada 18 Desember 1946 di Ci...

Hotel Hollywood RooseveltLetak7000 Hollywood Blvd.Hollywood, Los Angeles, CaliforniaDibangun1927ArsitekFisher, Lake & TraverArsitekturKebangkitan Kolonial SpanyolBadan pengelolaSwasta Los Angeles Historic-Cultural MonumentDitetapkan1991[1]545 Lokasi Hotel Hollywood Roosevelt di Los Angeles Metropolitan Area Hotel Hollywood Roosevelt adalah sebuah hotel bersejarah yang dirancang dengan gaya Kebangkitan Kolonial Spanyol, yang terletak di 7000 Hollywood Boulevard di Hollywood, Los An...

Єва Бандровська-Турськапол. Ewa Bandrowska-Turska Народилася 20 травня 1894(1894-05-20)[1]Краків, Королівство Галичини та Володимирії, Долитавщина, Австро-Угорщина[2][3]Померла 25 червня 1979(1979-06-25)[2] (85 років)Варшава, Польська Народна Республіка[2]Поховання Повонзківський ц

Pato Donald Personaje de The Walt Disney Company Primera aparición The Wise Little Hen (1934)Creado por Dick LundyWalt DisneyInterpretado por Clarence NashTony AnselmoDaniel RossVoz original Clarence Nash (1934–1985)Tony Anselmo (1985–presente)Daniel Ross (Solo en Mickey Mouse Mixed-Up Adventures)Doblador en España Héctor Lera (90s-2019)Antonio Acaso (2019-presente)Doblador en Hispanoamérica Jaime Iranzo (1951-1970s)Clarence Nash (1934-1950 1984)Ruy Cuevas (1987-2004)Erick Salinas (20...

Henning Verlage auf dem Amphi Festival 2009 Henning Verlage (* 16. Mai 1978 in Greven, Münsterland) ist ein deutscher Musikproduzent und Keyboarder. Inhaltsverzeichnis 1 Leben 2 Diskografie 3 Weblinks 4 Einzelnachweise Leben Bereits in jungen Jahren erhielt er Orgelunterricht und spielte E- und Kirchenorgel. Als Teenager experimentierte Verlage mit Keyboards und einem Atari-Computer und beschloss, das Hobby zum Beruf zu machen.[1] Von 1995 bis ca. 2000 war er Keyboarder der Amateur-B...

Adriaan Johan Charles de Neve Adriaan Johan Charles de Neve (Padang, Hindia Belanda (kini Indonesia), 1857 - Den Haag, Belanda, 15 Januari 1913) adalah asisten residen Belanda di Aceh, residen di Divisi Barat Kalimantan dan Ksatria Militaire Willems-Orde. Karier Atas perannya sebagai asisten residen di Aceh, De Neve diangkat sebagai kesatria Militaire Willems-Orde berdasarkan Surat Keputusan no. 19 tgl. 19 Maret 1897. Kemudian, ia menjadi residen di Divisi Barat Kalimantan. Pada tahun 1892, i...

American basketball coach (born 1963) Brad UnderwoodUnderwood coaching against Michigan in January 2020Current positionTitleHead coachTeamIllinoisConferenceBig TenRecord120–80 (.600)Annual salary$3.4 millionBiographical detailsBorn (1963-12-14) December 14, 1963 (age 59)McPherson, Kansas, U.S.Playing career1982–1983Hardin–Simmons1983–1984Independence CC1984–1986Kansas State Position(s)GuardCoaching career (HC unless noted)1986-1987Hardin–Simmons (GA)1988–1992Dodge City CC1992

Auwines adalah seorang pengusaha restoran asal Indonesia. Putra Minangkabau asal Sungai Puar, Agam, Sumatera Barat ini merupakan pendiri jaringan Restoran Padang Sari Ratu. Ratu merujuk pada nama Ratu Plaza. Restorannya merupakan pioner rumah makan Padang di dalam plaza.[1] Pada mulanya ia merupakan pengusaha tekstil. Karena istrinya, Rosmaiyar pandai memasak, ia berpindah haluan ke bisnis rumah makan. Bisnis ini dimulainya pada tanggal 20 Maret 1982, dengan mendirikan resto pertama d...

Jerry SeinfeldSeinfeld pada tahun 2016Nama lahirJerome Allen SeinfeldLahir29 April 1954 (umur 69) Brooklyn, New York, Amerika Serikat.MediaLawakan tunggal, televisi, filmPendidikanMassapequa High SchoolAlma materSUNY OswegoQueens College (BA)Tahun aktif1976–kiniGenreKomedi pengamatan, humor sureal, komedia kulit hitam, cringe comedy, deadpan, satireSubjekKebudayaan Amerika Serikat, Politik Amerika Serikat, kehidupan sehari-hari, perbedaan gender, perilaku manusia, kecanggungan sos...

First mandatory prayer of the day in Islam Fajr redirects here. For other uses, see Fajr (disambiguation). Fajr prayerDawn on CorsicaOfficial nameصلاة الفجر، صلاة الصبح، صلاة الغداةAlso calledDawn prayerObserved byMuslimsTypeIslamicSignificanceA Muslim prayer offered to God at the dawn hour of the morning.ObservancesFajr nafl prayer (رغيبة الفجر)BeginsAstronomical DawnEndsSunriseFrequencyDailyRelated toSalah, Qunut, Five Pillars of Islam Part ...

  لمعانٍ أخرى، طالع كلارنس (توضيح). كلارنسClarence الشعار الأصلي النوع مغامرة كوميديا بطولة كلارنس ، جيف ، سومو ، ماري ، تشاد، بيلسون. البلد  الولايات المتحدة لغة العمل العربية الإنجليزية عدد المواسم 8 عدد الحلقات 300 (قائمة الحلقات) مدة الحلقة 11 دقيقة قائمة الحلقات قائمة ...

Liste schwedischer Erfinder und Entdecker in alphabetischer Reihenfolge des Familiennamens. Liste Inhaltsverzeichnis A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A Karl Johan Andersson: Entdeckung des Okawango und der Etoscha-Pfanne Anders Jonas Ångström. Anders Jonas Ångström: Mitbegründer der Astrospektroskopie Johan August Arfwedson: Chemiker, Entdeckung des chemischen Elementes Lithium Svante Arrhenius: (Nobelpreis) – Nachweis, dass Salze im Wasser als Ionen vorliegen. Ernst...

Auto race held at Martinsville Speedway in 1957 1957 Virginia 500 Race details[1] Race 17 of 53 in the 1957 NASCAR Grand National Series season 1957 Virginia 500 program coverDate May 19, 1957 (1957-May-19)Official name Virginia 500Location Martinsville Speedway, Martinsville, VirginiaCourse Permanent racing facility0.525 mi (0.844 km)Distance 441 laps, 231 mi (372 km)Scheduled Distance 500 laps, 262.5 mi (442.4 km)Weather Temperatures of 81 °F (27 °C); wind...

2021 Ring of Honor pay-per-view Final Battle (2021)Promotional poster featuring various ROH wrestlersPromotionRing of HonorDateDecember 11, 2021CityBaltimore, MarylandVenueChesapeake Employers Insurance ArenaTagline(s)The End of an EraEvent chronology ← PreviousDeath Before Dishonor Next →Supercard of Honor Final Battle chronology ← Previous2020 Next →2022 The 2021 Final Battle was the 20th Final Battle professional wrestling pay-per-view event produced by American...

Location of India Wildlife of India Biodiversity Flora Fauna Lists Amphibians Ants Birds Butterflies Fish Mammals Molluscs Moths Odonates Tiger beetles Reptiles Spiders Endangered animals Protected areas Biosphere reserves Wildlife sanctuaries Conservation areas Private protected areas Reserved andprotected forests Conservation andcommunity reserves Communal forests Lists National parks Ramsar Sites Conservation Projects Tiger Elephant Acts of Parliament Indian Forest Act 1927 Wildlife Protec...

1998 single by Janet Jackson Every TimeU.S. promotional coverSingle by Janet Jacksonfrom the album The Velvet Rope B-sideAccept MeReleasedMarch 25, 1998 (1998-03-25)GenrePopLength4:17LabelVirginSongwriter(s) Janet Jackson James Harris III Terry Lewis René Elizondo Jr. Producer(s) Janet Jackson Jimmy Jam and Terry Lewis Janet Jackson singles chronology You (1998) Every Time (1998) What's It Gonna Be?! (1999) Music videoEvery Time on YouTube Every Time is a song by American sing...

سحابة جزيئية من غبار وغازات تنفصل من سديم القاعدة التقطها تلسكوب هابل الفضائي. يبلغ عرض الصورة التي التقطت نحو 2 سنة ضوئية. ولادة النجوم وسط بين نجمي غيمة جزيئية كرة بوك سديم مظلم جرم نجمي فتي نجم أولي نجم تي الثور نجم قبل النسق الأساسي هيربيغ أي/ نجم بي سديم شمسي أصناف الأجر...

Valley in Canada Matapedia ValleyVallée de la MatapédiaLandscape in the Matapedia Valley at the junction of the Matapedia and Restigouche riversMatapedia ValleyGaspésie–Îles-de-la-Madeleine,  Quebec,  CanadaLength375 km (233 mi) southwestGeologyTyperiver valleyGeographyPopulation centersAmquiCoordinates48°30′N 67°20′W / 48.500°N 67.333°W / 48.500; -67.333 Traversed by Route 132 The Matapedia Valley (French: vallée de la Mata...

Lukas Graham Lukas Graham 2016年基本情報出身地  デンマーク コペンハーゲンジャンル Popsoul活動期間 2011年 -レーベル Copenhagen RecordsWarnerThen We Take the World公式サイト lukasgraham.comメンバー Lukas ForchhammerMark FalgrenMagnus Larsson旧メンバー Anders KirkKasper DaugaardMorten Ristorp ルーカス・グラハム(Lukas Graham)は、デンマークコペンハーゲン出身のソウル・ポップ・バンド。ルーカス・フォ...

M.Syamsul LuthfiS.E.Anggota Dewan Perwakilan Rakyat Republik IndonesiaPetahanaMulai menjabat 1 Oktober 2019PresidenJoko WidodoDaerah pemilihanNusa Tenggara Barat IIMasa jabatan1 Oktober 2014 – 23 September 2018PresidenSusilo Bambang Yudhoyono Joko WidodoPenggantiNanang SamodraDaerah pemilihanNusa Tenggara Barat Wakil Bupati Lombok Timur ke-2Masa jabatan31 Agustus 2008 – 31 Agustus 2013PresidenSusilo Bambang YudhoyonoGubernurAbdul Malik (Plh.) Muhammad Zainul Majd...

Kembali kehalaman sebelumnya