reectrix
reectrix

Reputation: 8629

Is there a way to return an empty string for a null object in Groovy when setting values in a constructor?

I know Groovy has the null check operator ?, where you can do something like: params.name? which will check if it's null, and return null. Is there a way to return the empty string instead of a null? Something like:

params.name? "" : params.name

When you're creating a new object and you're passing in a value for the class variables, like:

Foo myObj = new Foo(name : params.name? "" : params.name)

Upvotes: 9

Views: 15716

Answers (1)

cfrick
cfrick

Reputation: 37073

you have the order wrong here. x ? y : x would return x, if x is null (falsey). Turn that code around: params.name ? params.name : "" or even shorter: params.name ?: ""

Also ? is no operator in groovy. Both the ? and : form the Ternary Operator or the shorter version ?: called the Elvis Operator

Upvotes: 19

Related Questions