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

kot*_*oto 13 groovy

首先,我知道' Groovy String to int '的问题及其响应.我是Groovy语言的新手,现在正在玩一些基础知识.将String转换为int的最简单方法似乎是:

int value = "99".toInteger()
Run Code Online (Sandbox Code Playgroud)

要么:

int value = Integer.parseInt("99")
Run Code Online (Sandbox Code Playgroud)

这些都有效,但对这些答案的评论让我感到困惑.第一种方法

String.toInteger()
已弃用,如groovy文档中所述.我也认为

Integer.parseInt()
利用核心Java功能.

所以我的问题是:是否有任何合法的,纯粹​​的groovy方式来执行将String转换为int这样一个简单的任务?

Sea*_*ull 28

我可能错了,但我认为大多数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)
Run Code Online (Sandbox Code Playgroud)

如果要获取null而不是异常,请使用已链接的答案中的配方.

def toIntOrNull = { it?.isInteger() ? it.toInteger() : null }
assert 100 == toIntOrNull("100")
assert null == toIntOrNull(null)
assert null == toIntOrNull("abcd")
Run Code Online (Sandbox Code Playgroud)

  • @koto恭喜您成功开始StackOverflow!=) (2认同)