首先,我知道问题' Groovy String to int '这是回应。我是 Groovy 语言的新手,现在正在玩一些基础知识。将 String 转换为 int 的最直接方法似乎是:
int value = "99".toInteger()
或者:
int value = Integer.parseInt("99")
这些都有效,但对这些答案的评论让我感到困惑。如 groovy 文档中所述,第一个 methodString.toInteger() 已被弃用。我也假设
Integer.parseInt() 使用了核心 Java 特性。
所以我的问题是:是否有任何合法的、纯粹的方式来执行将 String 转换为 int 这样简单的任务?
最佳答案
我可能是错的,但我认为大多数 Grooviest 方法是使用安全强制转换 "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")
关于groovy - 如何在 Groovy 中以正确的方式将 String 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36007867/