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 toString
method for Groovy's null
object to return an empty string instead of null
.
def a = [a:null, b:'foobar']
println "${a.a} ${a.b}"
org.codehaus.groovy.runtime.NullObject.metaClass.toString = {return ''}
println "${a.a} ${a.b}"
This will print:
null foobar
foobar
If you only want to redefine toString
temporarily, add the following after your last print...
to change it back:
org.codehaus.groovy.runtime.NullObject.metaClass.toString = {return 'null'}
You can also change null
's toString
behavior using a Groovy Category
[1] [2]. For example:
@Category(org.codehaus.groovy.runtime.NullObject) class MyNullObjectCategory {def toString() {''}}
use (MyNullObjectCategory) {
println "${a.a} ${a.b}"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With