Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get rid of "null" when concating string in groovy?

Tags:

groovy

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?

like image 701
donnior Avatar asked May 09 '12 14:05

donnior


1 Answers

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}"
}
like image 110
Dan Cruz Avatar answered Oct 03 '22 20:10

Dan Cruz