As I mentioned in the question,
How can I use coalescing operator in Haxe?
As I mentioned in the question,
How can I use coalescing operator in Haxe?
Use this addon:
Then, type
var value = a || 'backup value';
instead of
var value = (a == null) ? 'backup value' : a;
You can also utilize abstracts instead of macros for this purpose
class Test {
static function main() {
trace("Haxe is great!");
var s:Ory<String> = "hi!";
trace(s || "I don't get picked");
s = null;
trace(s || "I get picked");
trace(s + "!");
}
}
@:forward abstract Ory<T>(T) from T to T {
@:op(a||b) public inline function or(b:T):Ory<T> {
return this != null ? this : b;
}
}
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:
It uses the existing
||
operator because macros can not introduce entirely new syntax.However, personally I would probably prefer a static extension like this:
Instead of making your own, you could also consider using the
safety
library, which has a number of additional static extensions forNull<T>
and features for dealing withnull
in general.