Language: Add "Safe" (nullable) cast operator `as?`

Created on 12 Jun 2019  路  6Comments  路  Source: dart-lang/language

It'll be a little enhancement but so much pleasant one :)

Kotlin and Swift has something like _Safe casting_ with as? operator. It gives an opportunity to casting with null fallback if cast can't be performed:

void someFunction(dynamic arg) {
  // we could has something like
  final classVariable = (arg as? SomeClass)?.someValue;

  // in place of
  final classVariable = arg is SomeClass ? arg.someValue : null;
}

Most helpful comment

I like it, too! I missed this when I came from C#

All 6 comments

Thanks for filing an issue - just a head up, this issue tracker is for issues with the website. Language feature requests can be filed at https://github.com/dart-lang/language

Ahh, you're right, sorry ;)

Moved to the language repo!

I like this. I was honestly just about to file a request for the exact same thing (thanks to GitHub for listing relevant existing issues!)

Another practical use case would be;

int x = o as? int ?? 0;  // Could perhaps use some parentheses for readability :)

This is the safe cast operator that was originally requested when the current as operator was added, and it is very useful in a number of situations. See C# for prior art.

I like it, too! I missed this when I came from C#

Definitely something I miss from Kotlin. Would be great timing to have this implemented this alongside the upcoming null safety.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

munificent picture munificent  路  5Comments

stategen picture stategen  路  4Comments

lrhn picture lrhn  路  4Comments

marcelgarus picture marcelgarus  路  3Comments

panthe picture panthe  路  4Comments