Applying operations after type conversion error

74 Views Asked by At

I have converted using a string into the int. But it has two classes That doesn't have any arithematic or logical operation associated.

string x = "42";
int|error  y = int:fromString(x);
y=y+1;
2

There are 2 best solutions below

0
ThisaruG On BEST ANSWER

This is by design. When you perform string to int conversion, there can be errors. There is no way the compiler can know beforehand the resulting type. Therefore, the int:fromString() function returns a union type consisting int and the error type.

In Ballerina, there are a couple of ways to handle this. The easiest way is to use the check expression, which is used to early return the error value if an error occurred, and if there's not an error, assign the value to the intended type. Look at the following code:

public function main() returns error? {
    string x = "42";
    int y = check int:fromString(x);
    y += 1; // This is as same as the `y = y + 1;`
}

In the above function, if there's an error in converting the string value to an int value, the error is returned. Otherwise the value is assigned to the variable y. Note that the function has the return type error?, which is a must to use the check expression here.

1
sanoJ On

You can have an error check and do the necessary arithmetic operations in the else block as follows,

string x = "42";
int|error y = int:fromString(x);

if(y is error) {
    io:println("Error occurred in conversion");
} else {
    y = y + 1;
    io:println(y);
}