Question

Here's the crux of what I don't understand:

% groovysh
Groovy Shell (1.8.6, JVM: 1.6.0_21)
Type 'help' or '\h' for help.
------------------------------------------------------
groovy:000> class vars {
groovy:001> static int x = 1;
groovy:002> }
===> true
groovy:000> println new vars().x
1
===> null
groovy:000> println vars.x
ERROR groovy.lang.MissingPropertyException:
No such property: vars for class: groovysh_evaluate
Possible solutions: class
        at groovysh_evaluate.run (groovysh_evaluate:2)
        ...

If vars resolves to something in the expression new vars().x, why not also in the expression vars.x? It's like a phantom identifier that only actually exists for purposes of instantiation.

Was it helpful?

Solution

Your code doesn't work because you are using the wrong naming conventions. You should write the class with a capital V. This way the Groovy shell knows you are referring to a class, instead of a variable, in case the Groovy cannot determine it.

This is what you really want:

groovy:000> class Vars {
groovy:001>     static int x = 1
groovy:002> }
===> true
groovy:000> Vars.x
===> 1

Hope that helps!

OTHER TIPS

Your problem is that vars is a class, not an object, and x is not declared as a static property. The best practice is to always name your classes with an upper case letter to prevent this kind of confusion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top