groovyclosuresgstring

Elvis operator in GString in Groovy


String someMethod(def columnOne, int number, columnName){
     return columnOne + '-' + number + "${ -> (columnName == '') ?: '-' + columnName}"
}

and when I call it with:

someMethod('one', 2, '')

I get the following result:

one-2true

Why the closure returns true but not the '' or -somehting


Solution

  • You don't need the elvis here but the regular ternary, like this:

    (columnName ? '-'+columnName : '')
    

    Elvis is short for x ?: y => x ? x : y and the result of columnName=='' then simply is true and this will print.