2

This question is about the code behaviour I observed. I have given 3 cases.

def data = [:] // some map with data that has map values
def tag = "Some String from Config"
def results = []

// A) This worked
if(data."$tag") {
  // need first key of the inner map
  results << data."$tag".keySet().toArray()[0] ?: 0
} else {
  results << 0
}

//B) Did not work
results << data."$tag" ? (data."$tag".keySet().toArray()[0] ?: 0) : 0 // Gave Null pointer exception


//C) Did not work
results << data."$tag" ?.keySet().toArray()[0] ?: 0 // Gave Null pointer exception

I am not sure why but this behaviour I observed. Ideally B and C statements should also work like A. Am I missing something here ? What is wrong ?

Groovy version : 2.2.2 Java : 7

9
  • does it work if you use complets << (...)?
    – cfrick
    Dec 16, 2014 at 21:33
  • 1
    Pedant alert: Thats the Groovy Elvis operator. The ternary operator exists in groovy and java and needs two different arguments after the question mark on either side of the colon. It's called the elvis operator because if you turn ?: on its side it's an elvis emoticon Dec 16, 2014 at 21:35
  • @cfrick No I tried. But <pre> () </pre? should not make difference here right ? Dec 16, 2014 at 21:36
  • @MattCoubrough Yes you are right, slipped through :) Not sure Pedant though Dec 16, 2014 at 21:36
  • but B has both (elvis and ternary)
    – cfrick
    Dec 16, 2014 at 21:37

1 Answer 1

4

B and C fail due to the precedence of the operators (. .? (dots) > << > ?:; see http://docs.codehaus.org/display/GROOVY/JN2535-Control Operator Overloading -- sorry found no better reference).

def data = [:]
def tag = "sometag"

def r1 = []
r1 << data."$tag"?.keySet()?.first() ?: 0
// implies (r1 << data."$tag"?.keySet()?.first()) ?: 0
assert r1==[null]

def r2 = []
r2 << (data."$tag"?.keySet()?.first() ?: 0)
assert r2==[0]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.