Groovy Order of Operations Gotcha: Ternary Operator vs. Left Shift

The code below perplexed the heck out of me until a co-worker helped me understand the problem.

List items = []
items << row.policy_no
items << row.insured_name
items << row.effective_date ? row.effective_date.format('MM/dd/yyyy') : 'not available'
items.each { item ->
    println item
}

No matter what I did, I could not seem to get the value for effective_date to format.

What is happening here is that Groovy is evaluating the left shift operator (<<) before the ternary operator (?:).  I was able to get this code to do what I wanted simply by wrapping the expression in parentheses.

items << row.effective_date ? row.effective_date.format('MM/dd/yyyy') : 'not available' )

My first impression is that this would seem to be a bug, or at least undesirable behavior on Groovy’s part. But there is probably a good reason for it that I’m not seeing.

Advertisements

#groovy, #left-shift, #order-of-operations, #ternary-operator