Why can't typed optional arguments have a defa

2019-06-20 06:47发布

In ActionScript 3, when you declare an optional argument by giving it a default value, the value null cannot be used on typed arguments.

function Action(Param:int=null){
    // 1184: Incompatible default value of type Null where int is expected.
}
function Action(Param:int=0){
    // No compiler errors
} 

Any workarounds for this, or general purpose values that can apply to all data types?

3条回答
Explosion°爆炸
2楼-- · 2019-06-20 06:53

int variables cannot be null, that's why you get that error, only reference types like objects can be null

Instead you can use NaN as a special number instead of null. If you want to check if something is NaN you mus use the isNaN function.

查看更多
劫难
3楼-- · 2019-06-20 07:01

You can change your int to Number and then can set it to NaN which is a special number that means 'not a number' and this can represent your null state for a Number.

To check if something is NaN, you must use the isNaN() function and not val == NaN, or you will not get what you expect.

function Action(param:Number = NaN) : void {
    trace(param);
}

For all other objects, you can set them to null, but 'primitive' numbers are handled differently in Actionscript.

查看更多
倾城 Initia
4楼-- · 2019-06-20 07:12

you could also include a flag in the method signature to avoid having the parameter promoted from int to number:

function whatever(intProvided:Boolean = false, someInt:int = 0):void
{
    if(intProvided)
        doSomeStuff();
}
查看更多
登录 后发表回答