groovy - 如何在 Groovy 中以正确的方式将 String 转换为 int

标签 groovy

首先,我知道问题' 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/

相关文章:

grails - 使用 grails 可搜索插件的 apache lucene 索引文件的默认路径在哪里?

java - 如何使用Groovy脚本查找文件中是否存在特定字符串?

groovy - 闭包是如何执行的?

Grails 每用户数据库身份验证

jenkins - 如何传递选择参数以调用 Jenkins 管道内的作业

xml - Groovy Xml Holder 返回 'null' 作为现有属性的值

java - 是否可以用 Spock 模拟枚举?

java - 如何使用 Java 中的 GroovyScriptEngine 加载字符串输入(groovy 脚本)

要在 Groovy 中映射的 XML 元素。使用 XMLSluper

xml - groovy GPATH 帮助