Friday, 18 January 2013

Be aware of the ordering of operators

I was working on some Groovy code that required to use of the Elvis operator and an operation involving the addition of two maps, like so:

utag_map = utag_map + attrs.extraParams ?: [:] //add any user defined data to the map

However, this was the issue I was getting when I run my tests

                java.lang.NullPointerException

What gives?

I figured it out, and the reason of that is because of the precedence of the operations. You will need to apply the parenthesis to the second part of the operation first!

Solution:

utag_map = utag_map + (attrs.extraParams ?: [:]) //add any user defined data to the map

No comments:

Post a Comment