Pubudu
Pubudu

Reputation: 994

Can I get the actual type of a union type variable?

Suppose I have a code snippet like below:

var value = foo(key);

match value {
    int intVal => return intVal;

    string|float|boolean|map|() x => {
        error err = { message: "Expected an 'int', but found '<type_of_x>'"  };
        throw err;
    }
}

foo() returns a union: int|string|float|boolean|map|()

In the above case, I'm expecting the return value to be of type 'int' and want to print an error if not, saying an int was expected but found type_of_x instead. Can this be done in Ballerina?

Upvotes: 2

Views: 265

Answers (3)

Sanjiva Weerawarana
Sanjiva Weerawarana

Reputation: 824

Let me add one more point - a given value can be of any number of types in Ballerina. That is because a type is a set of values and nothing prevents the same value being in more than one set.

Therefore the idea of "typeof" is really not possible.

Upvotes: 1

Sameera Jayasoma
Sameera Jayasoma

Reputation: 1610

Ballerina language does not have an operator similar to typeof at the moment. However, I can suggest an obvious, workaround extending Nuwan's solution.

function bar () returns int {
    var value = foo();

    string typeName;
    match value {
        int intVal => return intVal;
        string => typeName = "string";
        float => typeName = "float";
        boolean => typeName = "boolean";
        map => typeName = "map";
        () => typeName = "nil";
    }

    error err = { message: "Expected an 'int', but found '" + typeName + "'"  };
    throw err;
}

function foo() returns int|string|float|boolean|map|() {
    return "ddd";
}

Upvotes: 1

nuwanbando
nuwanbando

Reputation: 581

You can do like

function main(string... args) {
    var value = foo();
    match value {
        int val => {
            io:println(val);
        }
        any x => {
            error err = { message: "Expected an 'int', but found 'any'"  };
            throw err;
        }
    }
}

function foo() returns(any) {
    any myInt = "hello";
    return myInt;
}

Right now you cannot do typeof and tell the type, however foo() should be typed, and therefore you should know the options available. Therefore you can match against them.

Upvotes: 1

Related Questions