Reputation: 1065
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?
Upvotes: 12
Views: 12409
Reputation: 13
I think, a rather simple way of achieving it, i.e. removing null, is to concatenate the string and the use replace method.
myString=""
myString=myString + "Bla Bla"
myString.replace("null", '')
Upvotes: 0
Reputation: 15512
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}"
}
Upvotes: 11
Reputation: 19229
Not sure if simpler, but:
[a.name, a.address].findAll().join(' ')
You may of course combine it with Tim's toString suggestion.
Notice that if any of the values might be "falsy" (e.g. 0), it will filter it out. You can fix that doing:
[a.name, a.address].findAll {it != null}.join(' ')
Upvotes: 3
Reputation: 171194
You could implement a toString
method in your class like so:
class A{
String name
String address
String toString() {
"${name ?: ''} ${address ?: ''}".trim()
}
}
then do
def a = new A( address:'some address' )
println a
To get some address
printed out, but this still used the Elvis operator as you had in your question...
Not sure there's much simpler you can do...
Upvotes: 8