import ballerina/io;
public function main() {
int|string value = "10";
io:println(increment(value)); //Will panic
}
function increment(int|string value) returns int {
return <int>value + 1;
}
import ballerina/io;
public function main() {
int|string value = "10";
io:println(increment(value));
}
function increment(int|string value) returns int|error {
if value is int {
// Type of `value` is narrowed to `int`
return value + 1;
}
// Type of `value` is narrowed to `string`
return check int:fromString(value) + 1;
}
Never use a cast when the cast can actually panic. Use value:ensureType which is similar to a type cast, but returns an error instead of panicking.