Groovy Script

Groovy supports Dynamic Typing. Variables are defined using the keyword “def,” and the type of a variable does not need to be declared in advance. The compiler figures out the variable type at runtime and you can even the variable type.

Consider the following groovy example,

def x = 104
println x.getClass()
x = "Guru99"
println x.getClass()

Output

class java.lang.Integer
class java.lang.String

Note: You can still variable types like byte, short, int, long, etc with Groovy. But you cannot dynamically change the variable type as you have explicitly declared it.

Consider the following code:

int x = 104
println x
x = "Guru99"

It gives the following error

104
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Guru99' with class 'java.lang.String' to class 'int'
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Guru99' with class 'java.lang.String' to class 'int'
    at jdoodle.run(jdoodle.groovy:3)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Command exited with non-zero status 1

Groovy-Operators

  • Arithmetic operators: Add (+), Subtract (-), Multiplication (*), Division(/)
  • Relational operators: equal to (==), Not equal to (!=), Less than (<) Less than or equal to (<=), Greater than (>), Greater than or equal to (>=)
  • Logical operators: And (&&), Or(||), Not(!)
  • Bitwise operators: And(&), Or(|), (^), Xor or Exclusive-or operator
  • Assignment operators: Negation operator (~)

Groovy- Closures

A groovy closure is a piece of code wrapped as an object. It acts as a method or a function.

Example of simple closure

def myClosure = {
       println "My First Closure"	
}
myClosure()