2
def nullString = "String is NOT null"

def check = (nullString != null) ? nullString : "String is null"
def check2 = nullString ? nullString : "String is null"
def check3 = nullString ?: "String is null"

println check 
println check2
println check3

Tell me if I'm wrong, but these three ternary statements above should all do the same thing, namely print out "String is NOT null" if nulString is not null. If nullString is null, print out "String is null".

And I think you all agree, if I initialze a variable like nullString = "" it is not null. Just because "" is not null.

But when testing the code above with nullString = "" only the first one prints out "String is NOT null". The other two interpret "" as null. Why is that?

(Sorry for my english, I hope you understand what I'm trying to say)

1
  • 1
    Ternary doesn't check for null, it checks for truthfulness.
    – tim_yates
    Feb 26, 2015 at 19:41

2 Answers 2

11

The empty string is falsy in Groovy.

2
1

Empty string evaluates to false by default, this evaluates to true:

assert !""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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