How to convert a string to an int?

Viewed 627

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'
$
2 Answers

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);
}

From Ballerina swan lake release onward, you can simply do the type conversion. No additional imports are required.

public function main() {
    string x = "42";
    int|error y = int:fromString(x);
}
Related