Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

groovy

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)
like image 274
reectrix Avatar asked Mar 31 '15 14:03

reectrix


People also ask

Can we return null from constructor?

We can not return any value from constructor... A constructor does not return anything; the "new" operator returns an object that has been initialized using a constructor. If you really want a constructor that may return null, perhaps you should check out the factory method pattern.

Does an empty string return null?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string. isEmpty() || string.

Is empty string null in Groovy?

In Groovy, there is a subtle difference between a variable whose value is null and a variable whose value is the empty string. The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

How do I assign a null value in Groovy?

There is no concept of explicitly assigning null in a properties file. The closest you can get is an empty string as you can read here. Or you can simply not specify the key at all.


1 Answers

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

like image 138
cfrick Avatar answered Dec 31 '22 00:12

cfrick