Null-aware operators in Dart

Three new language features just landed in the latest dev channel build of the Dart! Collectively known as null-aware operators, these new features will help you reduce the code required to work with potentially null objects.

I'm excited for these new abilities, because typing less is always a good thing. Read on to learn more, and be sure to try these new features on Dart Pad.

??

Use ?? when you want to evaluate and return an expression IFF another expression resolves to null.

    exp ?? otherExp

is similar to

    ((x) => x == null ? otherExp : x)(exp)

??=

Use ??= when you want to assign a value to an object IFF that object is null. Otherwise, return the object.

    obj ??= value

is similar to

    ((x) => x == null ? obj = value : x)(obj)

?.

Use ?. when you want to call a method/getter on an object IFF that object is not null (otherwise, return null).

    obj?.method()

is similar to

    ((x) => x == null ? null : x.method())(obj)

You can chain ?. calls, for example:

    obj?.child?.child?.getter

If obj, or child1, or child2 are null, the entire expression returns null. Otherwise, getter is called and returned.

Try them today!

The easiest way to try null-aware operators is to use Dart Pad, our browser-based playground for Dart.

Or, download a 1.12-dev (or later) build of the Dart SDK to try these new features in the Dart VM, dart2js, and the Dart analyzer.

Popular posts from this blog

Lists and arrays in Dart

The 29 Healthiest Foods on the Planet

Converting Array to List in Scala