HaxeFoundation / haxe-evolution

Repository for maintaining proposal for changes to the Haxe programming language
111 stars 58 forks source link

[PROPOSAL] Optional chaining operator #102

Closed EliteMasterEric closed 1 year ago

EliteMasterEric commented 1 year ago

The optional chaining operator (?.) would access a property or call a function of an object in a similar manner to ..

However, unlike ., if the object whose property is accessed is null, or the function being called is null, null will be returned instead of throwing a Null Object Reference or Null Function Reference

Examples:

var a = { b: "Test" };
var c = null;

return a.b; // returns "Test"
return c.b; // throws an exception if c is null

return c?.b; // returns null if c or c.b is null

// Equivalent to 'return c?.b;'
if (c == null) return null;
return c.b;

Optional chaining operators can be nested:

return a?.b?.c?.d?.e?.f?.g; // returns null

// Equivalent code is long!
if (a == null) return null;
if (a.b == null) return null;
if (a.b.c == null) return null;
if (a.b.c.d == null) return null;
if (a.b.c.d.e == null) return null;
if (a.b.c.d.e.f == null) return null;
return a.b.c.d.e.f.g;

Optional chaining operators should also be used for function calls:

return a.b.callFunction(); // throws an exception if a or b is null.

return a?.b?.callFunction(); // returns null.

Optional chaining can also be used to validate function calls:

var onCompleteCb:Int->Void;

function onComplete(result:Int) {
    // If onCompleteCb is not null, it will be called.
    // If onCompleteCb is null, does nothing (returns null) rather than throwing an exception
    onCompleteCb?.(result);
}

Specifics

For specifics on niche cases and implementation, refer to how optional chaining is implemented in JavaScript.

haxiomic commented 1 year ago

Good news! This feature has already been accepted and will be coming in a future version of haxe, here’s the accepted proposal

https://github.com/HaxeFoundation/haxe-evolution/blob/master/proposals/0017-null-safe-navigation-operator.md

EliteMasterEric commented 1 year ago

I had searched for "optional chaining" but guess I wasn't thorough enough in my search terms.

Looks like it was already implemented in HaxeFoundation/haxe#10479 and HaxeFoundation/haxe#10561 and appears to be targeting Haxe 4.3.0.

Will close this issue since it's resolved but will leave it here so people searching will find it.