Under Review
over 2 years ago

Language feature: Null coalescing operator and optional chaining

Working with nulls is pretty painful at the moment, it's probably because I have monkeyC.typeCheckLevel as Strict. Two problems arises.

1. Problem: Optional chaining

Suppose I have variable `bitmap` with type `BufferedBitmapReference?` then handling all the nulls is pretty painful at the moment to get to the DC:

var ref = (bitmap != null ? bitmap.get() : null) as BufferedBitmap?;
var dc = ref != null ? ref.getDc() : null;

In other languages, like JavaScript and C# one could call it something like this:

var dc = bitmap?.get()?.getDc();

Above would type `dc` variable as Dc?

2. Problem: null coalescing ??

function initialize(
    params as { :width as Lang.Number, :height as Lang.Number }
) {
    var w = params.get(:width);
    var h = params.get(:height);
    width = w != null ? w : 150;
    height = h != null ? h : 150;
}

This could use `??` operator like in other languages like C#/JavaScript

function initialize(
    params as { :width as Lang.Number, :height as Lang.Number }
) {
    width = params.get(:width) ?? 150;
    height = params.get(:height) ?? 150;
}

Both of the above features would be mostly syntactic sugar, but adds readability a lot.

Thank you for considering.

  • Okay, thanks.

    wouldn't it be more useful if there was a get that could have a 2nd parameter for the default to return?

    One can use ?? in many other places too. e.g.

    var dc = bitmap?.get()?.getDc() ?? someotherwayToGetDc();

    It's more versatile than changing the `get`, my use case was just one example.

  • The 1st feature was already requested in another thread.
    Regarding the 2nd: wouldn't it be more useful if there was a get that could have a 2nd parameter for the default to return?

    params.get(:width, 150)

    this would return 150 if :width is not an existing key (not sure though what it should return if the key exists but the value is null ;)