12

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?

4 Answers 4

11

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}"
}
6
  • 4
    Building on your answer, you could also temporarily redefine it with a category: @Category(NullObject) class NullObjectCategory { String toString() { '' } }, and then use it wherever you want to squelch nulls: use (NullObjectCategory) { assert "$a.a $a.b" == ' foobar' } Commented May 9, 2012 at 15:19
  • thank you, this will solve my problem, I think no one want to get "null" when printing strings to users on webpages
    – donnior
    Commented May 9, 2012 at 15:20
  • @JustinPiper Good point! Thanks for extra input. Updating answer.
    – Go Dan
    Commented May 9, 2012 at 15:33
  • @donnior Glad to help. Don't forget to accept the answer that best resolved your question; see the FAQ How do I ask questions here? for more information. Accepting answers to your questions ensures the SO community will be more willing to help you in the future.
    – Go Dan
    Commented May 9, 2012 at 15:44
  • Just one question: have you guys thought of thread safety when coming up with this solution? Especially, the solution @JustinPiper came up with could be thread safe, i don't know if the use(Category) technique is bound to the current thread, but the initial solution I think is a little dangerous, if you only want to get rid of 'null' on the web page. Making the distinction between null and '' is important in a system log, for example. Commented May 10, 2012 at 8:45
8

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...

1
  • @donnior It's miles nicer than the same thing done in pure java... The smallest I can think of for that is: String.format( "%s %s", name == null ? "" : name, address == null ? "" : address ).trim() ;-)
    – tim_yates
    Commented May 9, 2012 at 14:28
3

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(' ')
1
  • for a map [1:false,2:true,3:null].findAll{it.value != null}
    – chim
    Commented Jul 17, 2012 at 9:44
0

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", '')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.