Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary shortcut on Groovy

Tags:

groovy

I know that the ternary operator is already a shortcut in itself, but I'm still wondering if there is a shortcut for this in groovy:

String typeFilter = (params?.type) ? params.type : ""

What I'm trying to do here is:

"If the HashMap params has a type key, assign the value of that key to typeFilter, otherwise, assign typeFilter with an empty string"

I'm thinking whether if I can avoid typing params?.type twice, or is this the shortest code for my given scenario? Thank you for your feedback.

like image 622
Gideon Avatar asked Oct 20 '25 05:10

Gideon


2 Answers

You effectively just described the elvis operator:

String typeFilter = params.type ?: ""

More on it here: http://docs.groovy-lang.org/latest/html/documentation/#_elvis_operator

Just make sure you understand the Groovy truth (http://mrhaki.blogspot.com/2009/08/groovy-goodness-tell-groovy-truth.html) especially when it comes to the value of 0 vs null vs empty. Consider this:

params.age = 0
...
// elsewhere in the code
params.age = params.age ?: 6 // if no age provided default to 6

This would set the params.age to 6 although if was already initialized with 0!

like image 145
defectus Avatar answered Oct 22 '25 00:10

defectus


Have you considered the corner-case of the key type having a null value? The Elvis operator will return the RHS if this happens. This may not matter in the context of what you are trying to achieve, but it isn't correct for your requirement (taken literally):

"If the HashMap params has a type key, assign the value of that key to typeFilter, otherwise, assign typeFilter with an empty string"

Examples. (I've used 'none' rather than an empty string to make the output clearer.)

println( [:].type ?: 'none' )
=> none

println( [type: 42].type ?: 'none' )
=> 42

// But do you want null or 'none' in this case?
println( [type: null].type ?: 'none' )
=> none
like image 42
Paul Avatar answered Oct 22 '25 02:10

Paul



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!