I have a String
that represents an integer value and would like to convert it to an int
. Is there a groovy equivalent of Java's Integer.parseInt(String)
?
Converting a string to int in Groovy
groovy
groovy
I have a String
that represents an integer value and would like to convert it to an int
. Is there a groovy equivalent of Java's Integer.parseInt(String)
?
Best Answer
Use the
toInteger()
method to convert aString
to anInteger
, e.g.An alternative, which avoids using a deprecated method (see below) is
If you need to check whether the
String
can be converted before performing the conversion, useDeprecation Update
In recent versions of Groovy one of the
toInteger()
methods has been deprecated. The following is taken fromorg.codehaus.groovy.runtime.StringGroovyMethods
in Groovy 2.4.4You can force the non-deprecated version of the method to be called using something awful like:
Personally, I much prefer: