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;
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;
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 consistingintand theerrortype.In Ballerina, there are a couple of ways to handle this. The easiest way is to use the
checkexpression, 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: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 typeerror?, which is a must to use the check expression here.