问题
any choice = io:readln("Enter choice 1 - 5: ");
I cannot seem to cast the input to an int.
Both check and match gives the same error
var intChoice = <int>choice;
match intChoice {
int value => c = value;
error err => io:println("error: " + err.message);
}
and
c = check <int>choice;
gives
error: 'string' cannot be cast to 'int'
I looked into https://ballerina.io/learn/by-example/type-conversion.html and also studied https://ballerina.io/learn/api-docs/ballerina/io.html#readln but no luck.
What am I doing wrong?
回答1:
Seems like it is a bug in the any -> int
conversion.
If you change the choice variable type to string
or change the variable definition statement to assignment statement using var
, both approaches will works. Please refer the below example.
import ballerina/io;
function main(string... args) {
// Change the any to string or var here.
string choice = io:readln("Enter choice 1 - 5: ");
int c = check <int>choice;
io:println(c);
var intChoice = <int>choice;
match intChoice {
int value => io:println(value);
error err => io:println("error: " + err.message);
}
}
Update - As @supun has mentioned below, it is not a bug in any->int
conversion, it is an implementation detail which I was not aware of.
回答2:
The current behavior is actually correct and infact is not a bug. Let me explain the behavior.
When you read an input as any choice = io:readln("Enter choice 1 - 5: ");
the choice
variable is of type any
and it would contain a string
value. However, the way any
to typeX
(in this case int
) works is that, it will check whether the actual value inside the any-typed variable is of typeX
(int), and if so, then do the conversion.
In this case, the actual value inside the any-typed variable choice
is string
. Now if we try to convert this to int
it will fail, for the reason that it does not contain an integer inside. So the correct aproach is to first get the string value inside the any-type variable, and then convert the string to int in a second step. See the below example:
import ballerina/io;
function main(string... args) {
any choice = io:readln("Enter choice 1 - 5: ");
string choiceStr = <string>choice;
int choiceInt = check <int> choiceStr;
io:println(choiceInt);
}
But of course, reading the cmd input directly to a string like: string choice = io:readln("Enter choice 1 - 5: ");
is the better solution.
来源:https://stackoverflow.com/questions/50666487/how-do-i-read-an-int-from-command-line-in-ballerina