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 atype
key, assign the value of that key totypeFilter
, otherwise, assigntypeFilter
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.
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
!
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 atype
key, assign the value of that key totypeFilter
, otherwise, assigntypeFilter
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With