4

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'
$
user272735
  • 10,473
  • 9
  • 65
  • 96
  • Could you try something like this: ```int val = check strVal;``` I'm no expert in ballerina but its something I found online. try using ```check``` prior to the cast. – Fletchy Oct 25 '19 at 17:45

2 Answers2

6

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);
}
Chanaka Lakmal
  • 1,112
  • 9
  • 19
  • 1
    Works perfectly. Documentation available in [fromString](https://ballerina.io/learn/api-docs/ballerina/lang.int/functions.html#fromString) Somehow I missed that in the first reading ... – user272735 Oct 25 '19 at 18:00
  • 2
    You can also import the builtin int package like this. `import ballerina/lang.'int;` and refer to functions as `int | error y = 'int:fromString(x);`. The identifiers start with `'` are called delimited identifiers. One use case would be to deal with keyword conflicts. – Sameera Jayasoma Oct 25 '19 at 18:31
5

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);
}
Tharik Kanaka
  • 2,490
  • 6
  • 31
  • 54
Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34