Groovy shorthand if else operator

11,602

Sounds like a job for the Elvis Operator

value="${item.sequence ?: 'new'}"

This will return item.sequence as long as it is truthy. If item.sequence is falsy, then it will return the second expression.

Share:
11,602
me-me
Author by

me-me

Updated on July 09, 2022

Comments

  • me-me
    me-me almost 2 years

    I'm trying to set a variable in a .gsp file with an object been passed to the view from the controller. 'item' is an object in this case with an attribute called 'sequence' So what I'm trying to do is set the var 'action' to the value of item.sequence and if item.sequence is null then set action value to the string "new".

    <g:set var="action" value= "${item.sequence?item.sequence:'new'}"/>
    

    Unfortunately, I'm getting the value of item.sequence and "new" together. Does anyone know how I can do this shorthand?