3

I use safe navigation operator to avoid NPEs like this

myInstance?.field1
myInstance?.field2
myInstance?.field3

To convert the code above in for loop i wrote

<g:each var="i" in="${ (1..<4 }">
    myInstance['field'+i]
</g:each>

How do I use the safe navigation operator on above code when I am retrieving values in hashmap format?
I looked into docs here but it does not have a similar example.

2 Answers 2

6

I would use this syntax:

myInstance?."field$i"
2
  • This worked, but is there a guide line on when to use single quotes and when to use double? I use them interchangeably but in this case only double quotes worked!
    – Sap
    Commented Feb 23, 2012 at 19:09
  • Double quotes work because along with the embedded expression ($i) it makes a GString, and there's special handling to get a property or invoke a method dynamically this way. Commented Feb 23, 2012 at 19:49
5

You could do:

<g:each var="i" in="${ (1..<4 }">
    ${myInstance?."field$i"}
</g:each>

Or, probably better (and neater in your code) would be to make this a tag and do it as you would above inside the pure groovy tag.

Not the answer you're looking for? Browse other questions tagged or ask your own question.