According to type conversion example a string to int conversion is made with int.convert()
. However in Ballerina 1.0.0 that doesn't work:
$ ballerina version
Ballerina 1.0.0
Language specification 2019R3
$ cat test.bal
public function main() {
string x = "42";
int|error y = int.convert(x);
}
$ ballerina build test.bal
Compiling source
test.bal
error: .::test.bal:3:19: undefined function 'convert'
$
Also <int>
as mentioned elsewhere here in SO doesn't work either:
$ ballerina version
Ballerina 1.0.0
Language specification 2019R3
$ cat test.bal
public function main() {
string x = "42";
int|error y = <int>x;
}
$ ballerina build test.bal
Compiling source
test.bal
error: .::test.bal:3:19: incompatible types: 'string' cannot be cast to 'int'
$
Ballerina v1.0 and later, you can convert string
to int
as follows:
import ballerina/lang.'int as langint;
public function main() {
string x = "42";
int|error y = langint:fromString(x);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With