Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if Integer is Null or numeric in groovy?

I have a service method and have to throw an error if method parameter is null/blank or not numeric.

Caller is sending an Integer value but in called method how to check if it is numeric or null.

ex:

def add(value1,value2){
 //have to check value1 is null/blank
 //check value1 is numeric

}

caller: class.add(10,20)

Any suggestions around would be appreciated.

like image 679
TP_JAVA Avatar asked May 07 '12 17:05

TP_JAVA


People also ask

Is integer in Groovy?

Groovy supports integer and floating point numbers. An integer is a value that does not include a fraction.

How do you check if a string is a number in Groovy?

Groovy adds several methods to the String class to see if the string value is a number. We can check for all kind of number type like Integer , Double , BigDecimal and more.

How do I declare an integer in Groovy?

Groovy supports all Java types (primitive and reference types). All primitives types are auto converted to their wrapper types. So int a = 2 will become Integer a = 2.


1 Answers

More concrete that the answer of Dan Cruz, you can use String.isInteger() method:

def isValidInteger(value) {
    value.toString().isInteger()
}

assert !isValidInteger(null)
assert !isValidInteger('')
assert !isValidInteger(1.7)
assert isValidInteger(10)

But what happens if we pass a String that looks like a Integer for our method:

assert !isValidInteger('10')  // FAILS

I think that the most simple solution is use the instanceof operator, all assert are valid:

def isValidInteger(value) {
    value instanceof Integer
}
like image 78
Arturo Herrero Avatar answered Sep 24 '22 08:09

Arturo Herrero