Ene*_* F. 4 haxe operators coalescing null-coalescing-operator
正如我在问题中提到的
如何在Haxe中使用合并运算符?
Haxe没有像C#的null合并运算符??。
话虽如此,有可能实现与macros类似的东西。似乎几年前有人已经编写了一个完全可以做到这一点的库。这是自述文件中的一个示例:
var s = Sys.args()[0];
var path = s || '/default/path/to/../';
Run Code Online (Sandbox Code Playgroud)
它使用现有的||运算符,因为宏无法引入全新的语法。
但是,个人而言,我可能更喜欢这样的静态扩展:
class StaticExtensions {
public static function or<T>(value:T, defaultValue:T):T {
return value == null ? defaultValue : value;
}
}
Run Code Online (Sandbox Code Playgroud)
using StaticExtensions;
class Main {
static public function main() {
var foo:String = null;
trace(foo.or("bar")); // bar
}
}
Run Code Online (Sandbox Code Playgroud)
除了自己制作之外,您还可以考虑使用safetylibrary,该库通常具有许多其他静态扩展Null<T>和功能来处理null。