Groovy 中的类型转换
我有两个问题。
我执行了以下代码来查找 $
的 ASCII 值:
def a = "\$"
def b = (int)a
println b //prints 36
嗯,我对答案很满意。但是当我尝试像这样反向执行时,我发现我遗漏了一些东西:
def a = 36
String b = a
println b // getting output only 36
问题1:
所以我的第一个问题是为什么它打印 36
而为什么不打印 $
?我这里错了吗?
好吧,如果相同的第一个代码块被重写为:
def a = "\$"
def b = a as int
println b
如果我运行这个程序,我会得到这样的错误:
Caught: java.lang.NumberFormatException: For input string: "$"
at T.run(T.groovy:2)
即使我试图做与以前相同的事情。我收到错误。
问题 2:
那么为什么 as
关键字在这里不起作用,并且 def a = (int)b
是否不等于到 <代码>def a = b as int?解释一下。
提前致谢。
I have two questions.
I did the following code to find the ASCII value of $
:
def a = "\$"
def b = (int)a
println b //prints 36
Well I'm happy with the answer. But when I tried to do it in reverse like this, I found I'm missing something :
def a = 36
String b = a
println b // getting output only 36
Question 1:
So my first question is why it prints 36
and why not $
? Am I wrong here?
Well if the same first code block is re-written as:
def a = "\$"
def b = a as int
println b
If I run this program I get an error like this :
Caught: java.lang.NumberFormatException: For input string: "$"
at T.run(T.groovy:2)
Even though I'm trying to do the same as before. I'm getting an error.
Question 2:
So why does the as
keyword doesn't work here and does def a = (int)b
is not equal to to def a = b as int
? Explain me.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你将一个字符串转换为 int 时,只要其中有一个字符就可以了,所以我们可以说你将一个 char 转换为 int ,当你尝试将 int 转换为字符串时,我认为它使用了 toString 方法或类似的方法。尝试将 36 转换为 char,你会看到你的 '$'
when you cast a string to int it's ok while you have one char in it, so we can say you cast a char to int, when you try to cast int to a string i think it uses toString method or something like that. Try to cast 36 to char and you'll see your '$'