4

As I mentioned in the question,

How can I use coalescing operator in Haxe?

Enes F.
  • 406
  • 6
  • 17
  • Starting with Haxe 4.3.0, the null coalescing operator is supported. https://github.com/HaxeFoundation/haxe/releases/tag/4.3.0 – CedX Apr 06 '23 at 20:17

3 Answers3

6

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.

Gama11
  • 31,714
  • 9
  • 78
  • 100
3

Use this addon:

https://github.com/skial/nco

Then, type

var value = a || 'backup value';

instead of

var value = (a == null) ? 'backup value' : a;

AnnoyinC
  • 426
  • 4
  • 17
1

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;
  }
}
YellowAfterlife
  • 2,967
  • 1
  • 16
  • 24
  • Hm.. good point, but not sure how practical this is because you have to type it as `Ory` first. – Gama11 Sep 03 '19 at 11:54
  • Since people [seem to] most often want this for optional argument processing and alike, typing those as Ory<> is relatively small price. – YellowAfterlife Sep 03 '19 at 17:26