It pains me to encapsulate every asType call asType a try/catch like this:
def b = "" def c try { c = b as Integer } catch (NumberFormatException) { c = null } println c
instead, I would like to write the following in my code:
def b = "" def c = b as Integer
and if b not well formatted, I want null be assigned c
So, how can I overload this default behavior for the asType operator?
Is it risky if I do this for my entire Grails application? Or is it the best solution to just create your own method (for example, asTypeSafe ) and name it? Do Groovy / Do Grails have some configuration settings regarding Groovy type conversion?
EDIT (for people interested in the implemented answer) Based on the accepted answer, I added the following code to my bootstrap.groovy file and it works great.
String.metaClass.asTypeSafe = {Class c -> try { delegate.asType(c) } catch (Exception) { return null } }
and I call it the following:
def myNum = myStr.asTypeSafe(Integer)
type-conversion grails groovy
fabien7474
source share