Null conditional operator in ActionScript

The ?. operator

Apache Royale adds support for the null conditional operator in ActionScript, which uses the symbol ?.. The expression a?.b works similarly to a member access expression, like a.b. The difference when using ?. is that, if the left operand is nullish, it will immediately return null instead of trying to access the right operand and throwing an exception.

Requires Apache Royale 0.9.10 or newer.

Code example

Consider the following code that uses the ?. operator to access the field a on the condition that the object is not nullish.

var obj:Object = null;
var resolved:Object = obj?.a;
trace(resolved); // null

If the expression obj.a were used instead of obj?.a, then an exception would be thrown instead.

If the object is not nullish, then it works similarly to regular member access.

var obj:Object = {a: 123.4};
var resolved:Object = obj?.a;
trace(resolved); // 123.4

Limitations of the null conditional operator in Royale

Other ActionScript compilers, such as the one in the Apache Flex SDK, may not recognize the null conditional operator. Attemping to pass ActionScript or MXML source code that contains null conditional operators to another compiler may result in compile-time errors. In other words, to write 100% portable ActionScript code that works with any compiler, avoid using null conditional operator and any of Royale’s other extensions to the ActionScript language.