I have a class
class A{
String name
String address
}
def a = new A()
a.address = "some address"
println "${a.name} ${a.address}" => "null some address"
Here a.name is null, so the string printed will contains “null”, however I hope the result is "some address" which ignore the null value.
I know I can use println "${a.name ?: ''} ${a.address ?: ''}" when printing, is there any simpler solution?
You could redefine the
toStringmethod for Groovy’snullobject to return an empty string instead ofnull.This will print:
If you only want to redefine
toStringtemporarily, add the following after your lastprint...to change it back:You can also change
null‘stoStringbehavior using a GroovyCategory[1] [2]. For example: