2

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

2
  • hmmm, (p.foo[bar]) + 3 works - maybe compiler is confused. Commented Oct 30, 2011 at 22:35
  • Wow, that is weird. Oddly, this works: (p.foo).bar + 3. I also tried using classes with defined properties instead, but got the same error! It looks like putting it in parentheses like that causes it to look for a package called p.foo with a class called bar. Commented Oct 31, 2011 at 4:58

1 Answer 1

3

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!)

Sign up to request clarification or add additional context in comments.

2 Comments

Do you consider this behaviour of the compiler/parser right or like an error/bug?
Unexpected, maybe, but definitely not a bug. Wrapping a single class is a standard way to cast. I don't see how this would ever be written this way normally, either.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.