Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a string in groovy by empty and not null?

Tags:

groovy

I know this may be very un-groovy of me, but I need to be able to store an empty string in an array. Based on what I have found it seems like this: string = '' ends up being the same as this string = null.

Is this true or am I missing something?

If it is true, how can I initialize a string and make it empty in groovy?

like image 966
Deric Plummer Avatar asked Nov 04 '25 22:11

Deric Plummer


2 Answers

Groovy does not consider '' as equal to null.

'' == null
===> false

Perhaps you read that in the context of boolean expressions, where the two are equivalent (both if(null) and if('') evaluate to false).

You can declare a string the usual way:

String str = ''
def str = ''
like image 123
ernest_k Avatar answered Nov 07 '25 16:11

ernest_k


You can add an empty string to an array, are you trying to perform some logic based on the values of the array that's making use of the groovy truth maybe?

def myArr = new String[3]
myArr[0] = 'hello'
myArr[1] = ''
myArr[2] = null
myArr.each{ println it }
// prints
hello

null  
// whereas the following...
myArr.each{ if (it) println it }​ 
// prints
hello
// and nothing else
like image 37
Mike W Avatar answered Nov 07 '25 16:11

Mike W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!