Search code examples
groovyconditional-statementsternary

reference variable used in ternary conditional? (ex: var?this:null)


Is there a way to reference the first part of a ?: statement in groovy?

For example, is there any way to shorten

def time = map.get('time') ? map.get('time').get('milliseconds') : null

to something like

def time = map.get('time') ? it.get('milliseconds') : null

, where "it" references the first part of the command?


Solution

  • It sounds like you just want to use the safe navigation operator:

    def time = map.get('time')?.get('milliseconds')
    

    If map.get('time') returns a null reference, the result of the overall expression will be null, and get('milliseconds') won't be called.