Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use coalescing operator in Haxe?

As I mentioned in the question,

How can I use coalescing operator in Haxe?

like image 409
Enes F. Avatar asked Dec 22 '22 21:12

Enes F.


1 Answers

Haxe does not have a null coalescing operator like C#'s ??.

That being said, it's possible to achieve something similar with macros. It looks like somebody has already written a library that does exactly this a few years ago. Here's an example from its readme:

var s = Sys.args()[0];
var path = s || '/default/path/to/../';

It uses the existing || operator because macros can not introduce entirely new syntax.


However, personally I would probably prefer a static extension like this:

class StaticExtensions {
    public static function or<T>(value:T, defaultValue:T):T {
        return value == null ? defaultValue : value;
    }
}
using StaticExtensions;

class Main {
    static public function main() {
        var foo:String = null;
        trace(foo.or("bar")); // bar
    }
}

Instead of making your own, you could also consider using the safety library, which has a number of additional static extensions for Null<T> and features for dealing with null in general.

like image 91
Gama11 Avatar answered Jan 31 '23 11:01

Gama11