首先,我知道问题'Groovy 字符串到 int https://stackoverflow.com/questions/1713481/groovy-string-to-int’这是回应。我是 Groovy 语言的新手,现在正在尝试一些基础知识。将 String 转换为 int 的最直接方法似乎是:
int value = "99".toInteger()
or:
int value = Integer.parseInt("99")
这两者都有效,但是对这些答案的评论让我感到困惑。第一种方法
String.toInteger()
is deprecated, as stated in groovy documentation. I also assume that
Integer.parseInt()
makes use of the core Java feature.
所以我的问题是:有没有合法,纯粹常规如何执行将 String 转换为 int 这样的简单任务?
我可能错了,但我认为最精彩方法是使用安全强制转换"123" as int
.
事实上,你有很多行为略有不同的方法,而且都是正确的。
"100" as Integer // can throw NumberFormatException
"100" as int // throws error when string is null. can throw NumberFormatException
"10".toInteger() // can throw NumberFormatException and NullPointerException
Integer.parseInt("10") // can throw NumberFormatException (for null too)
如果您想获得 null 而不是异常,请使用您链接的答案中的配方。
def toIntOrNull = { it?.isInteger() ? it.toInteger() : null }
assert 100 == toIntOrNull("100")
assert null == toIntOrNull(null)
assert null == toIntOrNull("abcd")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)