问号运算符'?'的含义Haxe中的论点之前 [英] Meaning of question mark operator '?' before arguments in Haxe

查看:113
本文介绍了问号运算符'?'的含义Haxe中的论点之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个功能签名有什么区别?

What is the difference between these two function signatures?

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

参数是否带有?前缀似乎都没有什么区别,两者都可以很好地编译.

It doesn't seem to make any difference whether argument is prefixed with ?, both compile fine.

推荐答案

在此示例中,确实没有理由使用?,但是有所不同.

There is indeed no reason to use ? in this example, but there is a difference.

静态类型的目标上,f(null)无法编译,因为基本类型IntFloatBool不在可为空 .但是,? 意味着可空性,这意味着

On a statically typed target, f(null) would not compile since the basic types Int, Float and Bool are not nullable there. However, the ? implies nullability, meaning that

function f(?i:Int)

实际上与

function f(i:Null<Int> = null)

如您所见,?有两个效果:

As you can see, the ? has two effects:

  • 添加了null 默认值,因此您可以在通话过程中省略i:f();
  • 类型是否包装在 Null<T> .尽管这在动态目标上没有什么区别,但通常在静态目标上具有运行时性能成本(再次:对于Int/Float/Bool参数,仅 ).
  • A null default value is added, so you can omit i during the call: f();
  • The type is wrapped in Null<T>. While this makes no difference on dynamic targets, it usually has a runtime performance cost on static targets (again: only for Int / Float / Bool arguments).

我能想到的为什么您希望基本类型的参数可以为空的唯一原因是启用可选参数跳过.在此示例中,调用f时,仅当i可为空时才能被跳过:

The only reason I can think of why you would want arguments with basic types to be nullable is to enable optional argument skipping. When calling f in this example, i can only be skipped if it is nullable:

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

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


请注意,如果您将默认值添加到可选参数,即使您显式传递null,也会使用该值:


Note that if you add a default value to an optional argument, that value will be used even if you explicitly pass null:

class Main {
    static function main() {
        f(); // 0
        f(null); // 0
    }

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

这篇关于问号运算符'?'的含义Haxe中的论点之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆