res1
res1

Reputation: 3640

Groovy : why this code doesn't work ? unable to resolve class

I have this test code:

def p = [:]

p.foo = [:]

p.foo.bar = 120

p.foo.bar - 3

(p.foo.bar) + 3

why on the last statement i get a compilation error : "unable to resolve class p.foo.bar "?

Thanks for the help

Groovy version 1.8.1

Upvotes: 2

Views: 1471

Answers (1)

OverZealous
OverZealous

Reputation: 39570

OK, I think I figured it out. I ran the AST browser against your sample script (using the GroovyConsole). It would only show an output at the Conversion phase. At this phase you can see how the script is converted. The key is that the last line is converted into this:

...
((1) as p.foo.bar)

This means that, apparently, it's trying to cast or convert the 1 into a class named p.foo.bar.

You can dig a little deeper and see that the parser is parsing the statement like this:

(p.foo.bar)(+1)

Which is the same as

(p.foo.bar)1

Therefore, the parser/compiler is seeing the + as a unary + operator. And that is why you are getting the error. (The way around it it to remove the parentheses, or swap the order of the arguments!)

Upvotes: 3

Related Questions