Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy console can't "remember" any variables - always says "unknown property"

In the Groovy shell you can type in commands, such as

def x = 1

and run them. That line comes back with:

groovy:000> > def x = 1
def x = 1
===> 1
groovy:000>

Now if I type:

 println(x) 

I get:

groovy:000> > println(x)
println(x)
Unknown property: x
groovy:000> 

So it seems that the console nor shell remembers object definitions, is this normal?

like image 335
John Little Avatar asked Nov 03 '14 15:11

John Little


1 Answers

This is standard behavior in the Groovy shell, not peculiar to the Grails shell. You probably don't want to def the variable. See the following:

~ $ groovysh
Groovy Shell (2.3.4, JVM: 1.7.0_45)
Type ':help' or ':h' for help.
-------------------------------------------------------------------------------
groovy:000> def x = 42
===> 42
groovy:000> x
Unknown property: x
groovy:000> y = 2112
===> 2112
groovy:000> y
===> 2112
groovy:000>

From http://beta.groovy-lang.org/groovysh.html

1.3.4. Variables

Shell variables are all untyped (ie. no def or other type information).

This will set a shell variable:

foo = "bar"

But, this will evaluate a local variable and will not be saved to the shell’s environment:

def foo = "bar"

You can change this behaviour by enabling interpreterMode

groovy:000> := interpreterMode
groovy:000> def x = 42
===> 42
groovy:000> x
===> 42
groovy:000>
like image 62
Jeff Scott Brown Avatar answered Oct 28 '22 17:10

Jeff Scott Brown