问号运算符“?”的含义在 Haxe 中的参数之前

Meaning of question mark operator '?' before arguments in Haxe

这两个函数签名有什么区别?

function f(?i:Int = 0) {}
function f(i:Int = 0) {}

参数是否以?为前缀似乎没有任何区别,都可以编译。

它们是两个不同的东西。一种 ?表示可选参数。所以if可以完全排除在函数调用之外,不会发生替换。

(x:Float = 12) 是默认参数。意思是如果它被排除在函数调用之外,将使用值 12。

确实没有理由在这个例子中使用?,但是有区别。

上一个statically typed target, f(null) would not compile since the basic types Int, Float and Bool are not nullable there. However, the ? implies nullability,意思是

function f(?i:Int)

其实和

是一样的
function f(i:Null<Int> = null)

如您所见,? 有两个作用:

  • 增加了一个nulldefault value,调用时可以省略if();
  • 类型包裹在Null<T>中。虽然这对动态目标没有影响,但它通常会对静态目标产生运行时性能成本(同样:only for Int / Float / Bool 参数)。

我能想到为什么您希望基本类型的参数可为空的唯一原因是启用可选参数跳过。本例中调用f时,i只有在可为空的情况下才能跳过:

class Main {
    static function main() {
        f("Test"); // 0, "Test"
    }

    static function f(?i:Int = 0, s:String) {
        trace(i, s);
    }
}

请注意,如果您将 default value 添加到可选参数,即使您显式传递 null:

也会使用该值
class Main {
    static function main() {
        f(); // 0
        f(null); // 0
    }

    static function f(?i:Int = 0) {
        trace(i);
    }
}