10

I run groovysh, and type the following code:

groovy:000> String s = "Hello"
===> Hello
groovy:000> s
ERROR groovy.lang.MissingPropertyException:
No such property: s for class: groovysh_evaluate
        at groovysh_evaluate.run (groovysh_evaluate:2)
        ...
groovy:000>

How to access the s here?

(If I change String s = "Hello" to s = "Hello", I can access it. But I want to know how to access it in the example)


UPDATE

I want to use String s = "Hello" to define a variable because I want to declare the type of it. For example, if I write:

Date date = []

The date will be a java.util.Date. But if I write:

date = []

It will be a ArrayList.

Freewind
  • 193,756
  • 157
  • 432
  • 708

3 Answers3

11

The expression s = "Hello" sets a shell variable, the expression String s = "Hello" sets a local variable which does not get saved to the shell's environment. Please see the Groovy Shell documentation for more information. I am not quite sure what you are trying to achieve but you might rather want to go with Groovy Console to evaluate Groovy scripts.

Benjamin Muschko
  • 32,442
  • 9
  • 61
  • 82
  • thank you, **groovy console** can let me do it. You mean, there is no way to get the `s` from `String s = ...` in `groovysh`, right? – Freewind Aug 21 '11 at 04:14
  • 1
    You could wrap it in a [function](http://groovy.codehaus.org/Groovy+Shell#GroovyShell-Functions) and return `s` whenever you need it. That would be another option. – Benjamin Muschko Aug 21 '11 at 12:20
1

simply set it to interpreterMode

groovy:000> :set interpreterMode

and you can just straightly use

Date date = []

ref: http://www.groovy-lang.org/groovysh.html#GroovyShell-InterpreterMode

Aizzat Suhardi
  • 753
  • 11
  • 19
  • 1
    TY. This is what I expected as a Python user. now I execute always `groovysh --define=interpreterMode` – jgomo3 May 07 '17 at 19:57
0

You can write

date = [] as Date

to make sure date really has type Date. I had a similar problem and used

bin = [1, 26, 42 ,7] as byte[]
bin.encodeBase64()
bollin
  • 185
  • 11