Skip to content

Add "safe navigation"/existential operator #41

Closed
@DartBot

Description

@DartBot

This issue was originally filed by [email protected]


I didn't find the "safe navigation"/existential operator in the specification. Please consider including something like what's available in

Coffeescript (http://jashkenas.github.com/coffee-script/#operators),

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

compiles to

    var zip, _ref;
    zip = typeof lottery.drawWinner === "function" ? (_ref = lottery.drawWinner().address) != null ? _ref.zipcode : void 0 : void 0;

Groovy (http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29)

The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception, like so:

def user = User.find( "admin" ) //this might be null if 'admin' does not exist
def streetName = user?.address?.street //streetName will be null if user or user.address is null - no NPE thrown

Ruby, etc.

Null checks are tedious and clutter code-- really, anything is better than if( foo != null && ....)

Metadata

Metadata

Assignees

Labels

area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).type-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