Skip to content

Language: Add null-conditional operators and null-propagation in Dart #21695

Closed
@DartBot

Description

@DartBot

This issue was originally filed by @Emasoft


It would be very useful to have Null-Conditional Operators and Null-Propagation in Dart.

The null-conditional has two syntax forms.

First, is available as a member operator, adding the question mark prior to the dot operator ( ?. ). When this is present if the value of the object is null, the null-conditional operator will return null. For example:

return value?.substring(0, length);

Second, is to use the question mark in combination with the index operator ( ?[…] ), causing indexing into collection only to occur if collection isn’t null. For example:

T? item = collection?[index];

Null-Propagation is a way to avoid null exceptions avoiding all additional invocations in the call chain if the operand is null. For example:

return value?.substring(0, length).padRight(3);

If .substring() is called via the null-conditional operator, and the null value?.substring() could seemingly return null, Null-Propagation will short-circuits the call to padRight(), and immediately returns null, avoiding the programming error that would otherwise result in a null reference exception.

See for example the C# implementation:
http://msdn.microsoft.com/en-us/magazine/dn802602.aspx

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).closed-duplicateClosed in favor of an existing reporttype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions