New Issue: Nilability ergonomics: optional chaining

17577, "vasslitvinov", "Nilability ergonomics: optional chaining", "2021-04-16T06:00:52Z"

Nilability ergonomics / convenience features have been proposed in #12614 and forked off into #16931. The first of them is the topic of #13639, already implemented.

This issue requests the second convenience feature that is akin to Swift's Optional Chaining

This feature is a shorthand for this kind of conditional expression:

if const xTemp = x then xTemp.someMethod() else nil

that uses this syntax, which is inspired by Swift:

x?.someMethod()

This syntax probably entails defining a new postfix operator ?. to differentiate from the the postfix ?, which is allowed only on types.

The semantics is clear when x is a class and someMethod() returns a class, nilable or non-nilable.

A design question is: should we allow it for other types? For non-classes, the semantics could be:

x?.someMethod()
// is equivalent to:
if x then x.someMethod() else <the default value of x.type>

A consideration here is whether the user can tell, from the result of the expression, whether the then or else branch was taken. It is possible in the case where x is a class and someMethod() returns a non-nilable class, otherwise it is not possible to tell.