Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the type of a parameter in Haxe

Tags:

arrays

haxe

I'm converting a JavaScript library to Haxe. It seems Haxe is very similar to JS, but in working I got a problem for function overwriting.

For example, in the following function param can be an an integer or an array.

JavaScript:

function testFn(param) {
    if (param.constructor.name == 'Array') {
        console.log('param is Array');
        // to do something for Array value
    } else if (typeof param === 'number') {
        console.log('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

Haxe:

function testFn(param: Dynamic) {
    if (Type.typeof(param) == 'Array') { // need the checking here
        trace('param is Array');
        // to do something for Array value
    } else if (Type.typeof(param) == TInt) {
        trace('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

Of course Haxe supports Type.typeof() but there isn't any ValueType for Array. How can I solve this problem?

like image 485
rener172846 Avatar asked Nov 17 '17 08:11

rener172846


Video Answer


1 Answers

In Haxe, you'd usually use Std.is() for this instead of Type.typeof():

if (Std.is(param, Array)) {
    trace('param is Array');
} else if (Std.is(param, Int)) {
    trace('param is Integer');
} else {
    trace('unknown type');
}

It's possible to use Type.typeof() as well, but less common - you can use pattern matching for this purpose. Arrays are of ValueType.TClass, which has a c:Class<Dynamic> parameter:

switch (Type.typeof(param)) {
    case TClass(Array):
        trace("param is Array");
    case TInt:
        trace("param is Int");
    case _:
        trace("unknown type");
}
like image 184
Gama11 Avatar answered Sep 19 '22 02:09

Gama11