Safe Operator for Duck Typing in Groovy/GSP

grails, groovy, gsp

Solution

I'm afraid Groovy's operators wont help you here. The safe navigation operator (`?.`) would help you if the reference on which you want to call a method could be null; and the Elvis operator (`?:`) would help you if your `x` property would be a property of all the objects, except that for some of them it might be null (something like `it.x ?: 'no x here'`).

In this case --i assume you are working with a collection of objects of different classes, some of them which do not have an `x` property-- you may ask the object if it has the property `x` (notice that if the object implements a method called `getX`, then `it.hasProperty('x')` will be true):

<g:each in="${myObjects}>
  ${it.hasProperty('x') ? it.x : 'no x here'}
</g:each>

Replace the `'no x here'` bit with whatever your fallback value might be. Also, you might consider using the `<g:if>`/`<g:else>` tags instead of the ternary operator if the logic for both options is more complicated than a simple expression :)

Problem

I'm new to Grails development, and I'm wondering what the standard way of handling this problem is: In a GSP, I'm iterating over a list of domain objects, many, but not all of which have a getX() method. I want to a tag that looks like this: ``` <g:each in="${myObjects}> ${it.x} </g:each> ``` However, since some of my object don't have a getX method, I am getting a 'No such property' exception. I would like it if there was some sort of operator like the 'safe operator' that prevents NPEs. Is there good way of handling this without doing an 'instanceof'?

Original source