Sergii Sergii - 1 year ago 80
Groovy Question

Groovy. How to ignore method call if parameter is null? Is it possible to use null safe operator for the method in my case?

My groovy code is bellow:

String start
String startParam
String end
String endParam
String rule
Period period
String exDates
PeriodList expected = new PeriodList(true)

// init variables...

VEvent event = new ContentBuilder().vevent {
dtstart(start, parameters: parameters() { value(startParam) })
dtend(end, parameters: parameters() { value(endParam) })
rrule(rule)
exdate(exDates)
}


It works correctly in general, but if some of parameters were not defined with non
null
value I get an exception:

java.lang.RuntimeException: Failed to create component for 'exdate' reason: java.lang.reflect.InvocationTargetException

at groovy.util.FactoryBuilderSupport.createNode(FactoryBuilderSupport.java:719)
at groovy.util.FactoryBuilderSupport.dispatchNodeCall(FactoryBuilderSupport.java:855)
at groovy.util.FactoryBuilderSupport.doInvokeMethod(FactoryBuilderSupport.java:779)
at groovy.util.FactoryBuilderSupport.invokeMethod(FactoryBuilderSupport.java:499)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeOnDelegationObjects(ClosureMetaClass.java:423)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:346)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at net.fortuna.ical4j.model.VEventRecurrenceParametrizedTest$_test_closure2.doCall(VEventRecurrenceTest.groovy:79)


Is it possible to protect the property call (ignore one if variable is
null
)? I checked documentation, there is
null-safe-operator
. How could I use one for this case for example?


exdate(exDates)


exdate
should not be called if
exDates
is null.

if I try

exdate(this.?exDates)


it won't help because null safe operator will not protect method call if value is null, beside that this code
exdate(this.?exDates)
has compile error.

Answer Source

Just check for it being null or empty before making the call:

VEvent event = new ContentBuilder().vevent {
    dtstart(start, parameters: parameters() { value(startParam) })
    dtend(end, parameters: parameters() { value(endParam) })
    rrule(rule)
    if (exDates) exdate(exDates)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download