How to convert String to int in Groovy the right way

删除回忆录丶 提交于 2021-02-06 10:13:06

问题


First of all, I am aware of question 'Groovy String to int' and it's responses. I am a newbe to Groovy language and right now playing around some basics. The most straightforward ways to convert String to int seem to be:

int value = "99".toInteger()

or:

int value = Integer.parseInt("99")

These both work, but comments to these answers got me confused. The first method

String.toInteger()
is deprecated, as stated in groovy documentation. I also assume that

Integer.parseInt()
makes use of the core Java feature.

So my question is: is there any legal, pure groovy way to perform such a simple task as converting String to an int?


回答1:


I might be wrong, but I think most Grooviest way would be using a safe cast "123" as int.

Really you have a lot of ways with slightly different behaviour, and all are correct.

"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)

If you want to get null instead of exception, use recipe from answer you have linked.

def toIntOrNull = { it?.isInteger() ? it.toInteger() : null }
assert 100 == toIntOrNull("100")
assert null == toIntOrNull(null)
assert null == toIntOrNull("abcd")



回答2:


If you want to convert a String which is a math expression, not just a single number, try groovy.lang.Script.evaluate(String expression):

print evaluate("1+1"); // note that evalute can throw CompilationFailedException


来源:https://stackoverflow.com/questions/36007867/how-to-convert-string-to-int-in-groovy-the-right-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!