16

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?

Community
  • 1
  • 1
koto
  • 720
  • 2
  • 9
  • 29
  • 2
    `String.toInteger` isn't deprecated, it was just moved to `CharSequence` (a String is a CharSequence) – tim_yates Mar 15 '16 at 10:18
  • Thanks @tim_yates, but according to http://docs.groovy-lang.org/latest/html/gapi/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#toInteger(java.lang.CharSequence) I think that CharSequence version is also deprecated. However, I now see that version for java.lang.Number isn't deprecated, but it is now clear to me when my String become a Number... – koto Mar 15 '16 at 10:26
  • Yeah, that's the internal docs. That method's deprecated, as it moved to a dfferent class... The interface docs are here: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/CharSequence.html#toInteger() – tim_yates Mar 15 '16 at 10:52
  • Ah, and it makes sense now :) So my worries about the clarity or purity were unnecessary, thanks! – koto Mar 15 '16 at 11:10

2 Answers2

31

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")
Seagull
  • 13,484
  • 2
  • 33
  • 45
0

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
Noam Manos
  • 15,216
  • 3
  • 86
  • 85
  • 3
    That seems a bit offtopic, as OP asked about Simple way to convert String to int. Evaluate of any kind opens a whole lot of security problems. Moreover, Script#evaluate is not recommended way to do what you suggest, but [groovy.util.Eval](http://docs.groovy-lang.org/latest/html/api/groovy/util/Eval.html) is. – Seagull Oct 12 '16 at 08:46