Как преобразовать строку в int? - PullRequest
1 голос
/ 25 октября 2019

В соответствии с типом преобразования , пример преобразования строки в int выполняется с int.convert(). Однако в Ballerina 1.0.0 это не работает:

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

Также <int> как уже упоминалось в другом месте здесь в SO также не работает:

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

1 Ответ

3 голосов
/ 25 октября 2019

Ballerina v1.0 и новее, вы можете конвертировать string в int следующим образом:

import ballerina/lang.'int as langint;

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