There are multiple methods in order to write Groovy code and we will be using the Groovy Shell – groovysh which is a command line application that allows to evaluate Groovy expressions. We can also define classes and run simple experiments with groovysh.
In order to launch and start using the Groovy shell, just open up the Shell Terminal and type the following command:
groovysh
This will open up a Groovy Shell prompt similar to the output shown below:
Here you can type in the Groovy script and expressions to evaluate and generate results.
1+1
println "Hello world"
Just write the code and hit Enter and Groovy will evaluate the results and generate the output. If you write multi-line code, Groovy will automatically identify it and gets input for the subsequent lines. For example the following code:
class Person { def sayHello() { println "Hello there" } } person = new Person() person.sayHello()
In the above code we are writing multiple line of class code and then creating an object as the instance of the class and using the object, we are calling the method “sayHello()”. Groovy will read these multi lines of code as input and generates the proper output as below:
Thus the Groovy Shell groovysh is useful for writing small lines of code and experiment them. You can use the following help command to display various options that are available with the groovysh:
groovysh --help
We just wrote some expressions & code snippets on the Groovy Shell groovysh and saw how its useful to write small piece of experiment codes.