I am sick of encapsuling each call of asType
with try/catch
block like :
def b = ""
def c
try {
c = b as Integer
}
catch (NumberFormatException) {
c = null
}
println c
instead I would like to write in my code the following:
def b = ""
def c = b as Integer
and if b
is not well-formatted, then I want to have null
be assigned to c
So how can I overload this default behavior for the asType
operator ?
Is it risky if I do it for my entire Grails application? Or is the best solution to simply create a method of my own (like asTypeSafe
) and call it ? Do Groovy/Grails have some configuration tweaks regarding Groovy Type conversion?
EDIT (for people interested in the implemented answer) Based on the accepted answer, I have added the following code to my bootstrap.groovy file and it works perfectly.
String.metaClass.asTypeSafe = {Class c ->
try {
delegate.asType(c)
}
catch (Exception) {
return null
}
}
and I call it as below:
def myNum = myStr.asTypeSafe(Integer)