9

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)
reectrix
  • 7,999
  • 20
  • 53
  • 81
  • possible duplicate of [named parameters with default values in groovy](http://stackoverflow.com/questions/18001965/named-parameters-with-default-values-in-groovy) – Nathan Hughes Mar 31 '15 at 15:46

1 Answers1

19

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

cfrick
  • 35,203
  • 6
  • 56
  • 68