Groovy 将字符串分配给整数时的不一致行为

Groovy inconsistent behavior when assigning a string to an integer

当运行这段代码:

String number = "1"
Integer x
println number
x = number
println(x)

输出是:

1 49

当 运行 此代码时:

String number = "10"
Integer x
println number
x = number
println(x)

我得到:

10

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '10' with class 'java.lang.String' to class 'java.lang.Integer'

我知道这个问题可以用 toInteger 解决,最好不要陷入这种情况,但它的行为方式不一致,我对内部工作原理很好奇。

第一个示例的内部工作原理是字符 0ASCII encoding 是 48,1 是 49。

换句话说,表达式:

Integer x = "1"

要求 groovy 将字符 1 转换为一个整数,它很乐意这样做,并返回整数 ascii 值,即 49。java 中也会发生同样的情况:

char c = "1".charAt(0);
int i = (int) c;
System.out.println(i);

也打印 49。

这与字符串“10”相反,不再可能将这两个字符强制转换为单个 int(ascii 值),因为现在有两个字符。