How to "unwrap" union types? #36936
-
Hi all, I am new to Ballerina, so please excuse me if this has been asked somewhere before, but at least I can't find a way to do it in the official docs. If I have a float|error type variable, I cannot use it in math operations. So far, what I've been doing is something like this:
It seems wasteful to have a variable declared just for that. Is there a simpler way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi @tutiplain, float|error myFloat = 12;
if myFloat !is error { // using type narrowing
myFloat = myFloat * 12;
} public function main() returns error? {
float|error myFloat = 12;
myFloat = 12 * (check myFloat); // using check-expr
} Does this solve your problem? |
Beta Was this translation helpful? Give feedback.
-
FYI, You can use ballerina slack channel also to find answers to your questions, get support or learn how others are using Ballerina. https://ballerina.io/community/#ballerina-slack-community |
Beta Was this translation helpful? Give feedback.
Hi @tutiplain,
Math operations are not allowed with error types. So you have to ensure that the variable
myFloat
doesn't contain an error value before using it for math operations. IMO you can do it using either type narrowing or checking expressions.Does this solve your problem?