Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A more elegant way to cast in base groovy

I always seem to be needing to cast values in the params object in order to perform a .equals but it never feels right. If i use the parseXXX methods I also have to protect myself when the value is empty. It seems like there would be a better way to handle this in a dynamic language like Groovy. Has anyone found a different way that feels more like Groovy and less like Java? I could build a utility class to clean this up but I am looking for some built in functionality so please don't suggest additional libraries.

Example:

def intValue = (params.intValue)? Integer.parseInt(params.intValue) :null

Things.each{ thing -> 
    if (thing.intValue.equals(intValue)){
        //do stuff
    }
}
like image 887
Michael J. Lee Avatar asked Aug 12 '11 20:08

Michael J. Lee


2 Answers

What about using the Type Conversion Methods:

def intValue = params.int('myparam')

...there are also methods for boolean, long, char, short and so on. Each of these methods are null safe and safe from any parsing errors so you don't have to perform any addition checks on the parameters.

like image 153
Rob Hruska Avatar answered Oct 17 '22 03:10

Rob Hruska


I think that the most 'Groovy way' is as follows:

params.intValue as Integer == thing.intValue
like image 36
Artur Nowak Avatar answered Oct 17 '22 03:10

Artur Nowak